Skip to content

Commit

Permalink
fix: handle closing webContents in BrowserViews
Browse files Browse the repository at this point in the history
  • Loading branch information
codebytere committed Feb 27, 2023
1 parent edf887b commit 91e2353
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
3 changes: 3 additions & 0 deletions shell/browser/api/electron_api_browser_view.cc
Expand Up @@ -126,6 +126,9 @@ BrowserView::~BrowserView() {
}

void BrowserView::WebContentsDestroyed() {
if (owner_window())
owner_window()->window()->RemoveDraggableRegionProvider(this);

api_web_contents_ = nullptr;
web_contents_.Reset();
Unpin();
Expand Down
8 changes: 6 additions & 2 deletions shell/browser/api/electron_api_browser_window.cc
Expand Up @@ -112,6 +112,7 @@ BrowserWindow::~BrowserWindow() {
api_web_contents_->RemoveObserver(this);
// Destroy the WebContents.
OnCloseContents();
api_web_contents_->Destroy();
}
}

Expand Down Expand Up @@ -139,7 +140,6 @@ void BrowserWindow::WebContentsDestroyed() {

void BrowserWindow::OnCloseContents() {
BaseWindow::ResetBrowserViews();
api_web_contents_->Destroy();
}

void BrowserWindow::OnRendererResponsive(content::RenderProcessHost*) {
Expand Down Expand Up @@ -198,7 +198,11 @@ void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) {

// Trigger beforeunload events for associated BrowserViews.
for (NativeBrowserView* view : window_->browser_views()) {
auto* vwc = view->GetInspectableWebContents()->GetWebContents();
auto* iwc = view->GetInspectableWebContents();
if (!iwc)
continue;

auto* vwc = iwc->GetWebContents();
auto* api_web_contents = api::WebContents::From(vwc);

// Required to make beforeunload handler work.
Expand Down
4 changes: 1 addition & 3 deletions shell/browser/api/electron_api_web_contents.cc
Expand Up @@ -1222,9 +1222,7 @@ void WebContents::CloseContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();

// If there are observers, OnCloseContents will call Destroy()
if (observers_.empty())
Destroy();
Destroy();
}

void WebContents::ActivateContents(content::WebContents* source) {
Expand Down
9 changes: 9 additions & 0 deletions spec/api-browser-view-spec.ts
Expand Up @@ -345,6 +345,15 @@ describe('BrowserView module', () => {
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});

it('emits the destroyed event when webContents.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));

view.webContents.close();
await once(view.webContents, 'destroyed');
});
});

describe('window.open()', () => {
Expand Down

0 comments on commit 91e2353

Please sign in to comment.