diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc index 0043f9322028..bf2823f552ea 100644 --- a/shell/browser/api/electron_api_session.cc +++ b/shell/browser/api/electron_api_session.cc @@ -530,9 +530,10 @@ class DictionaryObserver final : public SpellcheckCustomDictionary::Observer { #endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) struct UserDataLink : base::SupportsUserData::Data { - explicit UserDataLink(Session* ses) : session(ses) {} + explicit UserDataLink(base::WeakPtr session_in) + : session{std::move(session_in)} {} - raw_ptr session; + base::WeakPtr session; }; const void* kElectronApiSessionKey = &kElectronApiSessionKey; @@ -552,8 +553,9 @@ Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context) protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8()); - browser_context->SetUserData(kElectronApiSessionKey, - std::make_unique(this)); + browser_context->SetUserData( + kElectronApiSessionKey, + std::make_unique(weak_factory_.GetWeakPtr())); #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckService* service = @@ -1512,7 +1514,7 @@ bool Session::IsSpellCheckerEnabled() const { Session* Session::FromBrowserContext(content::BrowserContext* context) { auto* data = static_cast(context->GetUserData(kElectronApiSessionKey)); - return data ? data->session : nullptr; + return data ? data->session.get() : nullptr; } // static diff --git a/shell/browser/api/electron_api_session.h b/shell/browser/api/electron_api_session.h index 1efe2296fa2e..e9ef22107312 100644 --- a/shell/browser/api/electron_api_session.h +++ b/shell/browser/api/electron_api_session.h @@ -10,6 +10,7 @@ #include #include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "base/values.h" #include "content/public/browser/download_manager.h" #include "electron/buildflags/buildflags.h" @@ -215,7 +216,9 @@ class Session : public gin::Wrappable, // The client id to enable the network throttler. base::UnguessableToken network_emulation_token_; - raw_ptr browser_context_; + const raw_ptr browser_context_; + + base::WeakPtrFactory weak_factory_{this}; }; } // namespace api