diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 599a46b1e6c0..a74a5697a9dc 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 bcf7df0a640b..aea43c89a0fd 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -3781,6 +3781,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; @@ -3798,7 +3804,7 @@ void Initialize(v8::Local exports, v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); - 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 25f7f507f45a..f5b73d896b01 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 () => {