Truly independent web browser
LibWeb+LibWebView+WebContent+UI/Qt: Tear down a closed tab's page
Aliaksandr Kalenike80c7ba83e77
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex b215349da5f..e61baf167dd 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -17,6 +17,7 @@#include <LibCompositing/Scrolling/AsyncScrollTree.h>#include <LibCompositing/Scrolling/AsyncScrollingState.h>#include <LibCore/EventLoop.h>+#include <LibCore/System.h>#include <LibCore/TimeZone.h>#include <LibGC/Heap.h>#include <LibGC/RootVector.h>@@ -2374,6 +2375,22 @@ void Internals::crash_remote_frame_processes()window().associated_document().page().client().crash_remote_frame_processes_for_testing();}+i32 Internals::web_content_process_id()+{+ return Core::System::getpid();+}++u32 Internals::document_count_in_this_process()+{+ auto documents = HTML::main_thread_event_loop().documents_in_this_event_loop_matching([](auto const&) { return true; });+ return documents.size();+}++void Internals::close_tab_through_ui_process()+{+ window().associated_document().page().client().close_tab_for_testing();+}+void Internals::stop_loading_through_ui_process(){window().associated_document().page().client().stop_loading_through_ui_process_for_testing();diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 91e6ee82604..90f7078a62a 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -255,6 +255,9 @@ public:bool has_populated_document(HTML::HTMLIFrameElement&);bool canvas_has_unpresented_content(HTML::HTMLCanvasElement&);void crash_remote_frame_processes();+ i32 web_content_process_id();+ u32 document_count_in_this_process();+ void close_tab_through_ui_process();void stop_loading_through_ui_process();void reload_through_ui_process();void reload_bypassing_cache_through_ui_process();diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex aa09ba083cb..8b12e05c87f 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -268,6 +268,11 @@ interface Internals {// Whether the canvas drew content that it has not presented to the compositor yet.boolean canvasHasUnpresentedContent(HTMLCanvasElement canvas);undefined crashRemoteFrameProcesses();+ long webContentProcessId();+ // The documents this process has not collected yet, whether or not they are still displayed.+ unsigned long documentCountInThisProcess();+ // Closes this tab as the browser's close button does when it has no beforeunload check to run.+ undefined closeTabThroughUIProcess();// Stops loading and reloads as the browser's Stop and Reload buttons do.undefined stopLoadingThroughUIProcess();undefined reloadThroughUIProcess();diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex c6cb091be5c..b06f90a2d78 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -756,6 +756,7 @@ public:virtual void page_did_destroy_child_frame(HTML::CrossProcessId) { }virtual String dump_site_isolation_process_tree_for_testing() { return {}; }virtual void crash_remote_frame_processes_for_testing() { }+ virtual void close_tab_for_testing() { }virtual void page_did_spoof_document_origin_for_testing(HTML::EnvironmentSettingsObject const&, URL::Origin const&) { }virtual void stop_loading_through_ui_process_for_testing() { }virtual void reload_through_ui_process_for_testing([[maybe_unused]] bool bypass_cache) { }diff --git a/Libraries/LibWebView/BlobURLStore.cpp b/Libraries/LibWebView/BlobURLStore.cppindex 7e2e133a162..303a30aa009 100644--- a/Libraries/LibWebView/BlobURLStore.cpp+++ b/Libraries/LibWebView/BlobURLStore.cpp@@ -105,6 +105,19 @@ void BlobURLStore::remove_entries_added_by(BlobURLEntryOwner const& owner)});}+void BlobURLStore::remove_entries_added_by(Vector<Utf16String> const& urls, BlobURLEntryOwner const& owner)+{+ for (auto const& url : urls) {+ auto entry = m_entries.get(url);+ if (!entry.has_value() || entry->revoked || owner_pointer(entry->added_by) != owner_pointer(owner))+ continue;++ entry->revoked = true;+ if (entry->handles == 0)+ remove_entry(url);+ }+}+void BlobURLStore::acquire(URL::BlobURLEntry::Token token){auto url = m_entry_urls_by_token.get(token);diff --git a/Libraries/LibWebView/BlobURLStore.h b/Libraries/LibWebView/BlobURLStore.hindex a0196d6b6df..2b20a73d47d 100644--- a/Libraries/LibWebView/BlobURLStore.h+++ b/Libraries/LibWebView/BlobURLStore.h@@ -33,6 +33,7 @@ public:URL::BlobURLEntry::Token add_entry(Utf16String url, Web::FileAPI::SerializedBlobURLEntry, BlobURLEntryOwner added_by, AddedByLocalFileContent = AddedByLocalFileContent::No);void remove_entries(Vector<Utf16String> const& urls, URL::Origin const& environment_origin, BlobURLEntryOwner const& removed_by);void remove_entries_added_by(BlobURLEntryOwner const&);+ void remove_entries_added_by(Vector<Utf16String> const& urls, BlobURLEntryOwner const&);Optional<Web::FileAPI::SerializedBlobURLEntry> resolve(Utf16String const& url, Optional<URL::BlobURLEntry::Token>) const;diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 0dd3e38b831..048d996dc43 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -142,9 +142,11 @@ ViewImplementation::~ViewImplementation()if (m_top_level_traversable) {m_top_level_traversable->discard_pending_host();- m_top_level_traversable->discard_representing_pages();if (page().is_open())page().client().close_page_of_closed_tab(page().id());+ // NB: After closing the page, which can leave a page of another process hosting an iframe of the tab to represent+ // the tab to a popup of the tab in that process.+ m_top_level_traversable->discard_representing_pages();}// A headless parent can own and destroy its child view without the child receiving a browsing-context-close@@ -5740,7 +5742,7 @@ Function<void()> ViewImplementation::prepare_for_close_without_prompting()};}-Function<void()> ViewImplementation::prepare_for_immediate_close()+void ViewImplementation::prepare_for_immediate_close(){VERIFY(!needs_beforeunload_check());@@ -5749,11 +5751,15 @@ Function<void()> ViewImplementation::prepare_for_immediate_close()set_debugger_paused(false);}- NonnullRefPtr closing_page = page();- closing_page->set_detached_close_pending(true);- return [closing_page = move(closing_page)] {- closing_page->async_request_close();- };+ page().set_detached_close_pending(true);+}++// The way a frontend closes a tab with no beforeunload check to run: the view goes without waiting for its page.+void ViewImplementation::close_tab_for_testing()+{+ prepare_for_immediate_close();+ if (on_close)+ on_close();}}diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex 4af47feb968..7957bd6a02b 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -574,7 +574,8 @@ public:void did_complete_close_preflight(Badge<WebContentPage>, u64 request_id, bool approved);Function<void()> prepare_for_close_without_prompting();void force_close();- Function<void()> prepare_for_immediate_close();+ void prepare_for_immediate_close();+ void close_tab_for_testing();bool needs_beforeunload_check() const;struct NavigationListener {diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex eba2b31db11..7a3d44297d4 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -61,6 +61,25 @@ Messages::WebContentClient::DidAddBlobUrlEntryResponse WebContentClient::did_addreturn URL::BlobURLEntry::Token { 0 };}+void WebContentClient::did_remove_blob_url_entries(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls)+{+ if (auto* page = this->page(page_id)) {+ page->did_remove_blob_url_entries(move(environment_id), move(urls));+ return;+ }++ // NB: A closed page's environments went with it, so its process can only revoke the entries it added itself.+ if (may_act_for_page(page_id))+ m_session->blob_url_store->remove_entries_added_by(urls, WeakPtr<WebContentClient> { *this });+}++void WebContentClient::close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)+{+ // NB: A page's workers are closed as its documents are destroyed, which happens after the tab's page has closed.+ if (may_act_for_page(page_id))+ WorkerProcessManager::the().close_worker_agent(*this, agent_id, owner_token);+}+bool WebContentClient::hosts_an_environment_with_storage_key(Web::StorageAPI::StorageKey const& storage_key){bool hosts_one = false;@@ -303,6 +322,8 @@ void WebContentClient::close_page_of_closed_tab(Web::PageId page_id)if (page->needs_beforeunload_check())page->set_detached_close_pending(false);PictureInPictureManager::the().close_window_and_its_page(*page);+ // NB: Other tabs can keep the process alive, so its page has to go as well.+ page->async_discard_embedded_page();page->close();}// Forgotten once the page is closed, so nothing registers it again.diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 8bce058eb1f..393c82533c9 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -89,6 +89,8 @@ public:static Optional<WebContentClient&> client_for_compositor_context_id(Web::CompositorContextId);virtual Messages::WebContentClient::DidAddBlobUrlEntryResponse did_add_blob_url_entry(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, Utf16String url, Web::FileAPI::SerializedBlobURLEntry entry) override;+ virtual void did_remove_blob_url_entries(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls) override;+ virtual void close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) override;virtual void did_retain_blob_url_token(Web::HTML::CrossProcessId navigable_id, URL::BlobURLEntry::Token token) override;virtual Messages::WebContentClient::DidRequestBlobUrlEntryResponse did_request_blob_url_entry(Utf16String url, Optional<URL::BlobURLEntry::Token> token) override;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 9fb80d15048..d023125b241 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -3341,11 +3341,6 @@ void WebContentPage::did_post_broadcast_channel_message(Web::HTML::PostedBroadcaWorkerProcessManager::the().post_broadcast_channel_message(move(message), *settings, client().pid(), client().is_private());}-void WebContentPage::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token)-{- WorkerProcessManager::the().close_worker_agent(client(), agent_id, owner_token);-}-void WebContentPage::rtc_transform_init(Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record){WorkerProcessManager::the().rtc_transform_init(client(), agent_id, transform_id, move(options_record));@@ -3418,6 +3413,12 @@ Messages::WebContentTestClient::DidRequestTabAudibilityChangeCountForTestingRespreturn view.has_value() ? view->playing_audio_indicator_change_count() : 0;}+void WebContentPage::did_request_close_tab_for_testing()+{+ if (displays_tab())+ view().close_tab_for_testing();+}+void WebContentPage::did_request_crash_of_remote_frame_processes_for_testing(){traversable().for_each_in_subtree([](CanonicalNavigable& child_frame) {diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 89ef04fd6e8..34cb8fa1203 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -255,7 +255,7 @@ private:virtual void did_request_dismiss_dialog() override;virtual void did_request_document_cookie_version_index(Web::HTML::EnvironmentId environment_id, i64 document_id, String domain) override;virtual void did_set_cookie(Optional<Web::HTML::EnvironmentId>, URL::URL, HTTP::Cookie::ParsedCookie, HTTP::Cookie::Source) override;- virtual void did_remove_blob_url_entries(Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls) override;+ void did_remove_blob_url_entries(Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls);Messages::WebContentClient::ConnectToStorageAreaResponse connect_to_storage_area(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id);virtual void did_change_needs_beforeunload_check(bool needs_beforeunload_check) override;virtual void did_consume_user_activation(Web::HTML::UserActivationConsumption consumption) override;@@ -388,7 +388,6 @@ private:Messages::WebContentClient::StartWorkerAgentResponse start_worker_agent(Web::HTML::WorkerAgentStartRequest request);Messages::WebContentClient::DidRequestStorageUsageResponse did_request_storage_usage(Web::HTML::EnvironmentId environment_id);virtual void did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message) override;- virtual void close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) override;virtual void rtc_transform_init(Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) override;virtual void rtc_transform_teardown(Web::HTML::WorkerAgentId agent_id, u64 transform_id) override;virtual void rtc_transform_encoded_audio_frame(Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) override;@@ -407,6 +406,7 @@ private:Messages::WebContentTestClient::DidRequestTabIsHeardPlayingAudioForTestingResponse did_request_tab_is_heard_playing_audio_for_testing();Messages::WebContentTestClient::DidRequestTabAudibilityChangeCountForTestingResponse did_request_tab_audibility_change_count_for_testing();virtual void did_request_crash_of_remote_frame_processes_for_testing() override;+ virtual void did_request_close_tab_for_testing() override;virtual void did_request_stop_loading_for_testing() override;virtual void did_request_reload_for_testing(bool bypass_cache) override;virtual void did_request_traverse_history_by_delta_for_testing(i32 delta) override;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 8d5fc4f3c42..88e82f01f66 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -1969,6 +1969,12 @@ void PageClient::crash_remote_frame_processes_for_testing()test_connection->async_did_request_crash_of_remote_frame_processes_for_testing(m_id);}+void PageClient::close_tab_for_testing()+{+ if (auto* test_connection = client().test_connection())+ test_connection->async_did_request_close_tab_for_testing(m_id);+}+void PageClient::page_did_spoof_document_origin_for_testing(Web::HTML::EnvironmentSettingsObject const& environment, URL::Origin const& origin){if (auto* test_connection = client().test_connection())diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex ae37ac1896c..a6371371b1f 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -226,6 +226,7 @@ private:virtual void page_did_destroy_child_frame(Web::HTML::CrossProcessId frame_id) override;virtual String dump_site_isolation_process_tree_for_testing() override;virtual void crash_remote_frame_processes_for_testing() override;+ virtual void close_tab_for_testing() override;virtual void page_did_spoof_document_origin_for_testing(Web::HTML::EnvironmentSettingsObject const&, URL::Origin const&) override;virtual void stop_loading_through_ui_process_for_testing() override;virtual void reload_through_ui_process_for_testing(bool bypass_cache) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex a40b27847f3..a0403a7aa74 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -83,7 +83,7 @@ endpoint WebContentClient routed by Web::PageId page_id{[NotRouted] did_add_blob_url_entry(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, Utf16String url, Web::FileAPI::SerializedBlobURLEntry entry) => (URL::BlobURLEntry::Token token)- did_remove_blob_url_entries(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls) => ()+ [NotRouted] did_remove_blob_url_entries(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls) => ()did_request_blob_url_entry(Utf16String url, Optional<URL::BlobURLEntry::Token> token) => (Optional<Web::FileAPI::SerializedBlobURLEntry> entry)did_retain_blob_url_token(Web::HTML::CrossProcessId navigable_id, URL::BlobURLEntry::Token token) =|@@ -320,7 +320,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_find_in_page(Web::PageId page_id, size_t current_match_index, Optional<size_t> total_match_count) =|[NotRouted] start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id)- close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|+ [NotRouted] close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|rtc_transform_init(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) =|rtc_transform_teardown(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id) =|rtc_transform_encoded_audio_frame(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) =|diff --git a/Services/WebContent/WebContentTestClient.ipc b/Services/WebContent/WebContentTestClient.ipcindex 20f720e7abf..6585d142c1d 100644--- a/Services/WebContent/WebContentTestClient.ipc+++ b/Services/WebContent/WebContentTestClient.ipc@@ -35,6 +35,7 @@ endpoint WebContentTestClient routed by Web::PageId page_id[NotRouted] did_request_tab_audibility_change_count_for_testing(Web::PageId page_id) => (u64 change_count)[NotRouted] did_request_has_populated_document_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) => (bool has_populated_document)did_request_crash_of_remote_frame_processes_for_testing(Web::PageId page_id) =|+ did_request_close_tab_for_testing(Web::PageId page_id) =|did_request_stop_loading_for_testing(Web::PageId page_id) =|did_request_reload_for_testing(Web::PageId page_id, bool bypass_cache) =|did_request_traverse_history_by_delta_for_testing(Web::PageId page_id, i32 delta) =|diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex c8e182e7912..30c347835bb 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -122,6 +122,10 @@ Text/input/SiteIsolation/iframe/isolated-iframe-finds-a-popup-of-its-top-level-bText/input/wpt-import/html/semantics/embedded-content/the-iframe-element/sandbox-top-close.sub.window.htmlText/input/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.html+; Hear from a same-origin tab over a BroadcastChannel.+Text/input/SiteIsolation/tab-closed-through-ui-process-is-torn-down.html+Text/input/SiteIsolation/tab-closed-with-its-popup-in-the-process-of-its-iframe.html+; Hear from a same-origin opener policy page over a BroadcastChannel.Text/input/SiteIsolation/popup-navigating-to-a-coop-page-leaves-its-opener.htmlText/input/SiteIsolation/popup-opened-onto-a-coop-page-leaves-its-opener.htmldiff --git a/Tests/LibWeb/Text/expected/SiteIsolation/tab-closed-through-ui-process-is-torn-down.txt b/Tests/LibWeb/Text/expected/SiteIsolation/tab-closed-through-ui-process-is-torn-down.txtnew file mode 100644index 00000000000..49880a65b5f--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/tab-closed-through-ui-process-is-torn-down.txt@@ -0,0 +1,10 @@+closed through the UI process: blob URL resolves while open: true+closed through the UI process: documents collected: true+closed through the UI process: tab stopped: true+closed through the UI process: worker stopped: true+closed through the UI process: blob URL revoked: true+closed by script: blob URL resolves while open: true+closed by script: documents collected: true+closed by script: tab stopped: true+closed by script: worker stopped: true+closed by script: blob URL revoked: truediff --git a/Tests/LibWeb/Text/expected/SiteIsolation/tab-closed-with-its-popup-in-the-process-of-its-iframe.txt b/Tests/LibWeb/Text/expected/SiteIsolation/tab-closed-with-its-popup-in-the-process-of-its-iframe.txtnew file mode 100644index 00000000000..49e8417c02e--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/tab-closed-with-its-popup-in-the-process-of-its-iframe.txt@@ -0,0 +1 @@+The UI process survived the tab closingdiff --git a/Tests/LibWeb/Text/input/SiteIsolation/tab-closed-through-ui-process-is-torn-down.html b/Tests/LibWeb/Text/input/SiteIsolation/tab-closed-through-ui-process-is-torn-down.htmlnew file mode 100644index 00000000000..afb30b36bee--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/tab-closed-through-ui-process-is-torn-down.html@@ -0,0 +1,98 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A closed tab goes from a process that other tabs keep alive: nothing of it keeps running or stays reachable.+ promiseTest(async () => {+ const httpServer = httpTestServer();++ // A collection sweeps in slices, so a document goes some time after it. Collecting away from this script's stack+ // keeps a stale value on that stack from keeping a closed tab's objects alive.+ const settledDocumentCount = async () => {+ let count = internals.documentCountInThisProcess();+ for (let stableRounds = 0; stableRounds < 10; ++stableRounds) {+ await internals.gcAsync();+ await timeout(20);+ if (internals.documentCountInThisProcess() !== count) {+ count = internals.documentCountInThisProcess();+ stableRounds = 0;+ }+ }+ return count;+ };++ const collectUntilDocumentCountIs = async count => {+ for (let attempt = 0; attempt < 1000; ++attempt) {+ await internals.gcAsync();+ if (internals.documentCountInThisProcess() <= count) return true;+ await timeout(10);+ }+ return false;+ };++ // A worker's process goes on for a while after its owner closes it.+ const stopsPinging = async (heard, pings) => {+ for (let attempt = 0; attempt < 100; ++attempt) {+ heard[pings] = 0;+ await timeout(200);+ if (heard[pings] === 0) return true;+ }+ return false;+ };++ const openTabAndHearFromIt = async closeRequestHandler => {+ const channelName = `closed-tab-${uniqueID()}`;+ const workerUrl = await httpServer.createEcho("GET", `/${channelName}-worker.js`, {+ status: 200,+ headers: { "Content-Type": "text/javascript" },+ body: `const channel = new BroadcastChannel(${JSON.stringify(channelName)});+ setInterval(() => channel.postMessage({ type: "worker-ping" }), 10);`,+ });+ const tabUrl = await httpServer.createEcho("GET", `/${channelName}.html`, {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>+ const channel = new BroadcastChannel(${JSON.stringify(channelName)});+ new Worker(${JSON.stringify(workerUrl)});+ setInterval(() => channel.postMessage({ type: "tab-ping" }), 10);+ channel.postMessage({ type: "blob-url", url: URL.createObjectURL(new Blob(["blob"])) });+ channel.onmessage = ({ data }) => { if (data.type === "close") { ${closeRequestHandler} } };+ <\/script>`,+ });++ const channel = new BroadcastChannel(channelName);+ const heard = { tabPings: 0, workerPings: 0, blobUrl: null };+ channel.onmessage = ({ data }) => {+ if (data.type === "tab-ping") ++heard.tabPings;+ else if (data.type === "worker-ping") ++heard.workerPings;+ else heard.blobUrl = data.url;+ };++ window.open(tabUrl, "_blank", "noopener");+ while (!heard.tabPings || !heard.workerPings || !heard.blobUrl) await timeout(10);+ return { channel, heard };+ };++ const closeTabAndReport = async (label, closeRequestHandler) => {+ const documentCountWithoutTheTab = await settledDocumentCount();++ const { channel, heard } = await openTabAndHearFromIt(closeRequestHandler);+ println(`${label}: blob URL resolves while open: ${(await fetch(heard.blobUrl)).ok}`);++ channel.postMessage({ type: "close" });+ println(`${label}: documents collected: ${await collectUntilDocumentCountIs(documentCountWithoutTheTab)}`);++ println(`${label}: tab stopped: ${await stopsPinging(heard, "tabPings")}`);+ println(`${label}: worker stopped: ${await stopsPinging(heard, "workerPings")}`);++ const blobUrlResolves = await fetch(heard.blobUrl).then(+ () => true,+ () => false+ );+ println(`${label}: blob URL revoked: ${!blobUrlResolves}`);+ channel.close();+ };++ await closeTabAndReport("closed through the UI process", "internals.closeTabThroughUIProcess();");+ await closeTabAndReport("closed by script", "window.close();");+ });+</script>diff --git a/Tests/LibWeb/Text/input/SiteIsolation/tab-closed-with-its-popup-in-the-process-of-its-iframe.html b/Tests/LibWeb/Text/input/SiteIsolation/tab-closed-with-its-popup-in-the-process-of-its-iframe.htmlnew file mode 100644index 00000000000..0a826c8aa39--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/tab-closed-with-its-popup-in-the-process-of-its-iframe.html@@ -0,0 +1,54 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A tab with an iframe in another process closes while its popup, of the iframe's site, is hosted in that process.+ // The page holding the iframe goes on representing the closed tab to the popup until the tab has let go of it.+ promiseTest(async () => {+ const httpServer = httpTestServer();+ const channelName = `closed-opener-${uniqueID()}`;+ const channel = new BroadcastChannel(channelName);++ const crossSiteHostname = uniqueLocalhostHostname("iframe-and-popup");+ const crossSiteUrl = async (name, body) => {+ const url = new URL(+ await httpServer.createEcho("GET", `/${channelName}-${name}`, {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body,+ })+ );+ url.hostname = crossSiteHostname;+ return url.href;+ };++ const iframeUrl = await crossSiteUrl("iframe", `<!DOCTYPE html><script>parent.postMessage("iframe", "*");<\/script>`);+ const popupUrl = await crossSiteUrl("popup", `<!DOCTYPE html><script>opener.postMessage("popup", "*");<\/script>`);++ const tabUrl = await httpServer.createEcho("GET", `/${channelName}-tab`, {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>+ const channel = new BroadcastChannel(${JSON.stringify(channelName)});+ const heard = new Set();+ addEventListener("message", ({ data }) => {+ heard.add(data);+ if (heard.size !== 2)+ return;+ channel.postMessage("closing");+ internals.closeTabThroughUIProcess();+ });+ const iframe = document.createElement("iframe");+ iframe.src = ${JSON.stringify(iframeUrl)};+ document.documentElement.appendChild(iframe);+ window.open(${JSON.stringify(popupUrl)});+ <\/script>`,+ });++ const closing = new Promise(resolve => (channel.onmessage = resolve));+ window.open(tabUrl, "_blank", "noopener");+ await closing;+ await timeout(500);+ println("The UI process survived the tab closing");+ channel.close();+ });+</script>diff --git a/UI/Qt/Tab.cpp b/UI/Qt/Tab.cppindex 14024ed1ea2..60047a303aa 100644--- a/UI/Qt/Tab.cpp+++ b/UI/Qt/Tab.cpp@@ -1645,9 +1645,8 @@ void Tab::request_close()m_preserve_close_retry_state_on_dialog_dismissal = false;if (!view().needs_beforeunload_check()) {- auto request_close = view().prepare_for_immediate_close();- if (m_window->definitely_close_tab(tab_index()))- Core::deferred_invoke(AK::move(request_close));+ view().prepare_for_immediate_close();+ m_window->definitely_close_tab(tab_index());return;}