diff --git a/atom/browser/api/atom_api_browser_view.cc b/atom/browser/api/atom_api_browser_view.cc index 57fb06fcd2a3..454ec3d5371d 100644 --- a/atom/browser/api/atom_api_browser_view.cc +++ b/atom/browser/api/atom_api_browser_view.cc @@ -154,6 +154,8 @@ void Initialize(v8::Local exports, isolate, BrowserView::GetConstructor(isolate)->GetFunction()); browser_view.SetMethod("fromId", &mate::TrackableObject::FromWeakMapID); + browser_view.SetMethod("getAllViews", + &mate::TrackableObject::GetAll); mate::Dictionary dict(isolate, exports); dict.Set("BrowserView", browser_view); } diff --git a/docs/api/browser-view.md b/docs/api/browser-view.md index 98d5c746add5..6ed06d4be4a8 100644 --- a/docs/api/browser-view.md +++ b/docs/api/browser-view.md @@ -40,6 +40,17 @@ view.webContents.loadURL('https://electronjs.org') ### Static Methods +#### `BrowserView.getAllViews()` + +Returns `BrowserView[]` - An array of all opened BrowserViews. + +#### `BrowserView.fromWebContents(webContents)` + +* `webContents` [WebContents](web-contents.md) + +Returns `BrowserView | null` - The BrowserView that owns the given `webContents` +or `null` if the contents are not owned by a BrowserView. + #### `BrowserView.fromId(id)` * `id` Integer diff --git a/lib/browser/api/browser-view.js b/lib/browser/api/browser-view.js index 60023fef92bb..9e7c81de5cbc 100644 --- a/lib/browser/api/browser-view.js +++ b/lib/browser/api/browser-view.js @@ -5,4 +5,12 @@ const {BrowserView} = process.atomBinding('browser_view') Object.setPrototypeOf(BrowserView.prototype, EventEmitter.prototype) +BrowserView.fromWebContents = (webContents) => { + for (const view of BrowserView.getAllViews()) { + if (view.webContents.equal(webContents)) return view + } + + return null +} + module.exports = BrowserView diff --git a/spec/api-browser-view-spec.js b/spec/api-browser-view-spec.js index 6debec2a7682..ab96021ebf4c 100644 --- a/spec/api-browser-view-spec.js +++ b/spec/api-browser-view-spec.js @@ -125,4 +125,26 @@ describe('BrowserView module', () => { assert.equal(view2.webContents.id, view.webContents.id) }) }) + + describe('BrowserView.fromWebContents()', () => { + it('returns the view with given id', () => { + view = new BrowserView() + w.setBrowserView(view) + assert.notEqual(view.id, null) + let view2 = BrowserView.fromWebContents(view.webContents) + assert.equal(view2.webContents.id, view.webContents.id) + }) + }) + + describe('BrowserView.getAllViews()', () => { + it('returns all views', () => { + view = new BrowserView() + w.setBrowserView(view) + assert.notEqual(view.id, null) + + const views = BrowserView.getAllViews() + assert.equal(views.length, 1) + assert.equal(views[0].webContents.id, view.webContents.id) + }) + }) })