From 324021a31b2532adf13c75b2a5a9c03f524bc78b Mon Sep 17 00:00:00 2001 From: Jeremy Rose Date: Mon, 23 Nov 2020 09:21:00 -0800 Subject: [PATCH] fix: segfault on webContents.fromId(xxx) (#26609) --- docs/api/web-contents.md | 3 ++- shell/browser/api/electron_api_web_contents.cc | 8 +++++++- spec-main/api-web-contents-spec.ts | 6 ++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 072374cf5b29e..e835925a9f6fa 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -42,7 +42,8 @@ returns `null`. * `id` Integer -Returns `WebContents` - A WebContents instance with the given ID. +Returns `WebContents` | undefined - A WebContents instance with the given ID, or +`undefined` if there is no WebContents associated with the given ID. ## Class: WebContents diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 1de35090d9a75..d24865b724469 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -3118,6 +3118,12 @@ namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; +gin::Handle WebContentsFromID(v8::Isolate* isolate, int32_t id) { + WebContents* contents = WebContents::FromID(id); + return contents ? gin::CreateHandle(isolate, contents) + : gin::Handle(); +} + std::vector> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector> list; @@ -3136,7 +3142,7 @@ void Initialize(v8::Local exports, gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("create", &WebContents::Create); - dict.SetMethod("fromId", &WebContents::FromID); + dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } diff --git a/spec-main/api-web-contents-spec.ts b/spec-main/api-web-contents-spec.ts index 1586afbe4e4c7..e38a2688ca78f 100644 --- a/spec-main/api-web-contents-spec.ts +++ b/spec-main/api-web-contents-spec.ts @@ -42,6 +42,12 @@ describe('webContents module', () => { }); }); + describe('fromId()', () => { + it('returns undefined for an unknown id', () => { + expect(webContents.fromId(12345)).to.be.undefined(); + }); + }); + describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined', async () => {