Skip to content

Truly independent web browser

LibWeb+WebContent+LibWebView: Add beforeunload prompt plumbing

Sam Atkins3543dc926d67
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 0516b38d925..c46ff9ba3ad 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -10683,7 +10683,10 @@ bool Document::showing_an_unload_prompt_is_unlikely_to_be_annoying_deceptive_or_
if (page().is_webdriver_active())
return false;
- return true;
+ // FIXME: Revisit this approximation of "unlikely to be annoying, deceptive, or pointless".
+ return is_active()
+ && is_fully_active()
+ && visibility_state() == HTML::VisibilityState::Visible;
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#steps-to-fire-beforeunload
@@ -10726,12 +10729,20 @@ Document::StepsToFireBeforeunloadResult Document::steps_to_fire_beforeunload(boo
unload_prompt_shown = true;
// FIXME: 2. Invoke WebDriver BiDi user prompt opened with document's relevant global object, "beforeunload", and "".
- // FIXME: 3. Ask the user to confirm that they wish to unload the document, and pause while waiting for the user's response.
-
- auto user_prompt_handler = WebDriver::get_the_prompt_handler(WebDriver::PromptType::BeforeUnload);
+ // 3. Ask the user to confirm that they wish to unload the document, and pause while waiting for the user's response.
+ auto top_level_traversable = page().top_level_traversable();
+ auto top_level_origin = top_level_traversable->active_document_origin();
+ auto top_level_url = top_level_traversable->active_document_url();
+ VERIFY(top_level_origin.has_value());
+ VERIFY(top_level_url.has_value());
+ auto source = top_level_origin->is_opaque()
+ ? MUST(String::formatted("{}://", top_level_url->scheme()))
+ : top_level_origin->serialize();
+ HTML::TemporaryExecutionContext context { relevant_settings_object() };
+ auto confirmed = page().did_request_before_unload(source, event_loop);
// 4. If the user did not confirm the page navigation, set unloadPromptCanceled to true.
- if (user_prompt_handler.handler == WebDriver::PromptHandler::Dismiss)
+ if (!confirmed)
unload_prompt_canceled = true;
// FIXME: 5. Invoke WebDriver BiDi user prompt closed with document's relevant global object and true if unloadPromptCanceled is false or false otherwise.
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index a85ecc184dd..8a6b0189f33 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -4313,6 +4313,10 @@ public:
, m_callback(callback)
, m_timeout(Platform::Timer::create_single_shot(heap(), TIMEOUT_MS, GC::create_function(heap(), [this] {
if (!m_completed) {
+ if (has_pending_before_unload_dialog()) {
+ m_timeout->restart();
+ return;
+ }
dbgln("FIXME: check_if_unloading_is_canceled timed out");
finish(Result::Continue);
}
@@ -4378,6 +4382,18 @@ public:
}
private:
+ bool has_pending_before_unload_dialog() const
+ {
+ if (m_traversable) {
+ if (auto active_document = m_traversable->active_document(); active_document && active_document->page().pending_dialog() == Page::PendingDialog::BeforeUnload)
+ return true;
+ }
+
+ return m_phase2_documents.find_if([](auto const& document) {
+ return document->page().pending_dialog() == Page::PendingDialog::BeforeUnload;
+ }) != m_phase2_documents.end();
+ }
+
void start_phase1()
{
// 4. Queue a global task on the navigation and traversal task source given traversable's active window to perform the following steps:
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index 25e4e1175da..d7883c5d819 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -1057,10 +1057,10 @@ void Page::did_complete_window_rect_request(u64 completion_id)
}
template<typename ResponseType>
-static ResponseType spin_event_loop_until_dialog_closed(PageClient& client, Optional<ResponseType>& response, SourceLocation location = SourceLocation::current())
+static ResponseType spin_event_loop_until_dialog_closed(PageClient& client, Optional<ResponseType>& response, HTML::EventLoop* event_loop = nullptr, SourceLocation location = SourceLocation::current())
{
- auto& event_loop = Web::HTML::current_settings_object().responsible_event_loop();
- auto pause_handle = event_loop.pause();
+ auto& responsible_event_loop = event_loop ? *event_loop : Web::HTML::current_settings_object().responsible_event_loop();
+ auto pause_handle = responsible_event_loop.pause();
Web::Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), [&]() {
return response.has_value() || !client.is_connection_open();
@@ -1093,6 +1093,22 @@ void Page::alert_closed()
}
}
+bool Page::did_request_before_unload(String const& source, HTML::EventLoop& event_loop)
+{
+ m_pending_dialog = PendingDialog::BeforeUnload;
+ m_client->page_did_request_before_unload(source);
+
+ return spin_event_loop_until_dialog_closed(*m_client, m_pending_before_unload_response, &event_loop);
+}
+
+void Page::before_unload_closed(bool accepted)
+{
+ if (m_pending_dialog == PendingDialog::BeforeUnload) {
+ m_pending_before_unload_response = accepted;
+ on_pending_dialog_closed();
+ }
+}
+
bool Page::did_request_confirm(Utf16String const& message)
{
m_pending_dialog = PendingDialog::Confirm;
@@ -1134,6 +1150,11 @@ void Page::prompt_closed(Optional<Utf16String> response)
// NB: A dialog blocks the whole tab, so every page of the tab holds the one a document of any of them opened.
void Page::did_open_dialog_in_another_process(PendingDialog dialog, Utf16String const& message)
{
+ if (dialog == PendingDialog::None) {
+ on_pending_dialog_closed();
+ return;
+ }
+
m_pending_dialog = dialog;
m_pending_dialog_text.clear();
if (!message.is_empty())
@@ -1150,6 +1171,7 @@ void Page::dismiss_dialog(GC::Ref<GC::Function<void()>> on_dialog_closed)
case PendingDialog::Alert:
m_client->page_did_request_accept_dialog();
break;
+ case PendingDialog::BeforeUnload:
case PendingDialog::Confirm:
case PendingDialog::Prompt:
m_client->page_did_request_dismiss_dialog();
@@ -1165,6 +1187,7 @@ void Page::accept_dialog(GC::Ref<GC::Function<void()>> on_dialog_closed)
case PendingDialog::None:
break;
case PendingDialog::Alert:
+ case PendingDialog::BeforeUnload:
case PendingDialog::Confirm:
case PendingDialog::Prompt:
m_client->page_did_request_accept_dialog();
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index 09c477c0464..ec8f3c75eb9 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -274,6 +274,9 @@ public:
void did_request_alert(Utf16String const& message);
void alert_closed();
+ bool did_request_before_unload(String const& source, HTML::EventLoop&);
+ void before_unload_closed(bool accepted);
+
bool did_request_confirm(Utf16String const& message);
void confirm_closed(bool accepted);
@@ -519,6 +522,7 @@ private:
PendingDialog m_pending_dialog { PendingDialog::None };
Optional<Utf16String> m_pending_dialog_text;
Optional<Empty> m_pending_alert_response;
+ Optional<bool> m_pending_before_unload_response;
Optional<bool> m_pending_confirm_response;
Optional<Optional<Utf16String>> m_pending_prompt_response;
GC::Ptr<GC::Function<void()>> m_on_pending_dialog_closed;
@@ -744,6 +748,7 @@ public:
virtual void page_did_unhover_link() { }
virtual void page_did_change_favicon(Gfx::Bitmap const&) { }
virtual void page_did_request_alert(Utf16String const&) { }
+ virtual void page_did_request_before_unload(String const&) { }
virtual void page_did_request_confirm(Utf16String const&) { }
virtual void page_did_request_prompt(Utf16String const&, Utf16String const&) { }
virtual void page_did_request_set_prompt_text(Utf16String const&) { }
diff --git a/Libraries/LibWeb/WebDriver/UserPrompt.cpp b/Libraries/LibWeb/WebDriver/UserPrompt.cpp
index 516e8bf572f..cce997a9407 100644
--- a/Libraries/LibWeb/WebDriver/UserPrompt.cpp
+++ b/Libraries/LibWeb/WebDriver/UserPrompt.cpp
@@ -25,11 +25,13 @@ void handle_any_user_prompts(Page& page, GC::Ref<GC::Function<void(Optional<Erro
// 3. If the current user prompt is an alert dialog, set type to "alert". Otherwise, if the current user prompt is a
// beforeunload dialog, set type to "beforeUnload". Otherwise, if the current user prompt is a confirm dialog,
// set type to "confirm". Otherwise, if the current user prompt is a prompt dialog, set type to "prompt".
- // FIXME: Handle beforeunload dialogs when they are implemented.
switch (page.pending_dialog()) {
case Page::PendingDialog::Alert:
type = PromptType::Alert;
break;
+ case Page::PendingDialog::BeforeUnload:
+ type = PromptType::BeforeUnload;
+ break;
case Page::PendingDialog::Confirm:
type = PromptType::Confirm;
break;
diff --git a/Libraries/LibWebCommon/Page/PendingDialog.h b/Libraries/LibWebCommon/Page/PendingDialog.h
index 842d412ccc4..3dd4027372b 100644
--- a/Libraries/LibWebCommon/Page/PendingDialog.h
+++ b/Libraries/LibWebCommon/Page/PendingDialog.h
@@ -11,6 +11,7 @@ namespace Web {
enum class PendingDialog {
None,
Alert,
+ BeforeUnload,
Confirm,
Prompt,
};
diff --git a/Libraries/LibWebView/HeadlessWebView.cpp b/Libraries/LibWebView/HeadlessWebView.cpp
index 40bbaa7ed9d..6f95ae3bdc4 100644
--- a/Libraries/LibWebView/HeadlessWebView.cpp
+++ b/Libraries/LibWebView/HeadlessWebView.cpp
@@ -110,6 +110,9 @@ HeadlessWebView::HeadlessWebView(Core::AnonymousBuffer theme, Web::DevicePixelSi
case Web::PendingDialog::Alert:
alert_closed();
break;
+ case Web::PendingDialog::BeforeUnload:
+ before_unload_closed(true);
+ break;
case Web::PendingDialog::Confirm:
confirm_closed(true);
break;
@@ -129,6 +132,9 @@ HeadlessWebView::HeadlessWebView(Core::AnonymousBuffer theme, Web::DevicePixelSi
case Web::PendingDialog::Alert:
alert_closed();
break;
+ case Web::PendingDialog::BeforeUnload:
+ before_unload_closed(false);
+ break;
case Web::PendingDialog::Confirm:
confirm_closed(false);
break;
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 570eb71b594..43519da80b2 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -2040,6 +2040,11 @@ void ViewImplementation::alert_closed()
});
}
+void ViewImplementation::before_unload_closed(bool accepted)
+{
+ page().routed_proxy()->async_before_unload_closed(page().id(), accepted);
+}
+
void ViewImplementation::confirm_closed(bool accepted)
{
traversable().for_each_hosting_page([&](WebContentPage& page) {
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index b07d64e7f0c..0ffc3327b7d 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -342,6 +342,7 @@ public:
Web::ViewportIsFullscreen is_fullscreen() const { return m_is_fullscreen; }
void alert_closed();
+ void before_unload_closed(bool accepted);
void confirm_closed(bool accepted);
void prompt_closed(Optional<Utf16String> const& response);
void color_picker_update(Optional<Color> picked_color, Web::HTML::ColorPickerUpdateState state);
@@ -457,6 +458,7 @@ public:
Function<void()> on_leave_tooltip_area;
Function<void(ContentBlockingSnapshot const&)> on_content_blocking_change;
Function<void(Utf16String const& message)> on_request_alert;
+ Function<void(String const& source, Function<void(bool)> on_complete)> on_request_before_unload;
Function<void(Utf16String const& message)> on_request_confirm;
Function<void(Utf16String const& message, Utf16String const& default_)> on_request_prompt;
Function<void(Utf16String const& message)> on_request_set_prompt_text;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index cc68b4e6590..19e126f0c80 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -2441,6 +2441,31 @@ void WebContentPage::did_request_alert(Utf16String message)
view().on_request_alert(message);
}
+void WebContentPage::did_request_before_unload(String source)
+{
+ did_open_dialog(Web::PendingDialog::BeforeUnload, {});
+ auto weak_traversable = m_traversable;
+ auto origin_page_id = id();
+ auto close_prompt = [weak_traversable, origin_page_id](bool accepted) {
+ if (!weak_traversable)
+ return;
+
+ weak_traversable->for_each_hosting_page([&](WebContentPage& page) {
+ if (page.id() != origin_page_id)
+ page.async_did_open_dialog_in_another_process(Web::PendingDialog::None, Utf16View {});
+ else
+ page.routed_proxy()->async_before_unload_closed(origin_page_id, accepted);
+ });
+ };
+
+ if (view().on_request_before_unload) {
+ view().on_request_before_unload(source, move(close_prompt));
+ return;
+ }
+
+ close_prompt(true);
+}
+
void WebContentPage::did_request_confirm(Utf16String message)
{
did_open_dialog(Web::PendingDialog::Confirm, message);
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index efe0c1a6b6c..dac844357fd 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -323,6 +323,7 @@ private:
virtual void did_get_debugger_object_properties(u64 request_id, Optional<String> error, DebuggerObjectProperties properties) override;
virtual void did_get_debugger_source_positions(u64 request_id, Vector<DebuggerSourcePosition> positions) override;
virtual void did_request_alert(Utf16String message) override;
+ virtual void did_request_before_unload(String source) override;
virtual void did_request_confirm(Utf16String message) override;
virtual void did_request_prompt(Utf16String message, Utf16String default_) override;
virtual void did_change_favicon(Gfx::ShareableBitmap favicon) override;
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 620e25f6e89..c523a57b425 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -3303,6 +3303,12 @@ void ConnectionFromClient::alert_closed(Web::PageId page_id)
page->page().alert_closed();
}
+void ConnectionFromClient::before_unload_closed(Web::PageId page_id, bool accepted)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().before_unload_closed(accepted);
+}
+
void ConnectionFromClient::confirm_closed(Web::PageId page_id, bool accepted)
{
if (auto page = this->page(page_id); page.has_value())
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index 6dd74967548..49bb1f5862e 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -266,6 +266,7 @@ private:
virtual void did_open_dialog_in_another_process(Web::PageId page_id, Web::Page::PendingDialog dialog, Utf16String message) override;
virtual void alert_closed(Web::PageId page_id) override;
+ virtual void before_unload_closed(Web::PageId page_id, bool accepted) override;
virtual void confirm_closed(Web::PageId page_id, bool accepted) override;
virtual void prompt_closed(Web::PageId page_id, Optional<Utf16String> response) override;
virtual void color_picker_update(Web::PageId page_id, Optional<Color> picked_color, Web::HTML::ColorPickerUpdateState state) override;
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index 88cc291ee62..de5dd96340f 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -1229,6 +1229,14 @@ void PageClient::alert_closed()
page().alert_closed();
}
+void PageClient::page_did_request_before_unload(String const& source)
+{
+ client().async_did_request_before_unload(m_id, source);
+
+ if (m_webdriver)
+ m_webdriver->page_did_open_dialog({});
+}
+
void PageClient::page_did_request_confirm(Utf16String const& message)
{
client().async_did_request_confirm(m_id, message);
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 1f4cd822017..824be97c768 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -263,6 +263,7 @@ private:
virtual void page_did_change_accessibility_focus(Web::UniqueNodeID) override;
virtual void page_did_request_alert(Utf16String const&) override;
+ virtual void page_did_request_before_unload(String const&) override;
virtual void page_did_request_confirm(Utf16String const&) override;
virtual void page_did_request_prompt(Utf16String const&, Utf16String const&) override;
virtual void page_did_request_set_prompt_text(Utf16String const&) override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 6a13129d853..f83bede3bd0 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -129,6 +129,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_request_image_context_menu(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, ByteString target, unsigned modifiers, Optional<Gfx::ShareableBitmap> bitmap) =|
did_request_media_context_menu(Web::PageId page_id, Web::HTML::CrossProcessId local_root_id, Gfx::IntPoint content_position, ByteString target, unsigned modifiers, Web::MediaContextMenu menu, Web::HTML::PreparedNavigationDescriptor navigation) =|
did_request_alert(Web::PageId page_id, Utf16String message) =|
+ did_request_before_unload(Web::PageId page_id, String source) =|
did_request_confirm(Web::PageId page_id, Utf16String message) =|
did_request_prompt(Web::PageId page_id, Utf16String message, Utf16String default_) =|
did_request_set_prompt_text(Web::PageId page_id, Utf16String message) =|
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index e72dcdd157f..bd9eccc4731 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -273,6 +273,7 @@ endpoint WebContentServer routed by Web::PageId page_id
did_open_dialog_in_another_process(Web::PageId page_id, Web::PendingDialog dialog, Utf16String message) =|
alert_closed(Web::PageId page_id) =|
+ before_unload_closed(Web::PageId page_id, bool accepted) =|
confirm_closed(Web::PageId page_id, bool accepted) =|
prompt_closed(Web::PageId page_id, Optional<Utf16String> response) =|
color_picker_update(Web::PageId page_id, Optional<Color> picked_color, Web::HTML::ColorPickerUpdateState state) =|
diff --git a/Services/WebContent/WebDriverConnection.cpp b/Services/WebContent/WebDriverConnection.cpp
index 8b80e47c83d..de536ec5839 100644
--- a/Services/WebContent/WebDriverConnection.cpp
+++ b/Services/WebContent/WebDriverConnection.cpp
@@ -2407,7 +2407,8 @@ Web::WebDriver::Response WebDriverConnection::send_alert_text(JsonValue payload)
break;
// -> Otherwise
- default:
+ case Web::Page::PendingDialog::BeforeUnload:
+ case Web::Page::PendingDialog::None:
// Return error with error code unsupported operation.
return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "Unknown dialog type"sv);
}
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index a484b3970a4..7d3fdfedd0b 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -148,6 +148,13 @@ if (NOT WIN32)
target_compile_definitions(TestBrowserHistoryTraversal PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")
endif()
+ add_executable(TestBeforeUnload TestBeforeUnload.cpp)
+ add_dependencies(TestBeforeUnload ladybird_build_resource_files ${ladybird_helper_processes})
+ target_link_libraries(TestBeforeUnload PRIVATE AK LibCore LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)
+ if (APPLE)
+ target_compile_definitions(TestBeforeUnload PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")
+ endif()
+
add_executable(TestInputMethodState TestInputMethodState.cpp)
add_dependencies(TestInputMethodState ladybird_build_resource_files ${ladybird_helper_processes})
target_link_libraries(TestInputMethodState PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)
@@ -345,6 +352,9 @@ if (BUILD_TESTING AND NOT WIN32)
add_test(NAME TestBrowserHistoryTraversal COMMAND $<TARGET_FILE:TestBrowserHistoryTraversal>)
set_tests_properties(TestBrowserHistoryTraversal PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
+ add_test(NAME TestBeforeUnload COMMAND $<TARGET_FILE:TestBeforeUnload>)
+ set_tests_properties(TestBeforeUnload PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
+
add_test(NAME TestInputMethodState COMMAND $<TARGET_FILE:TestInputMethodState>)
set_tests_properties(TestInputMethodState PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
diff --git a/Tests/LibWebView/TestBeforeUnload.cpp b/Tests/LibWebView/TestBeforeUnload.cpp
new file mode 100644
index 00000000000..a0bfa685057
--- /dev/null
+++ b/Tests/LibWebView/TestBeforeUnload.cpp
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/LexicalPath.h>
+#include <AK/Random.h>
+#include <AK/ScopeGuard.h>
+#include <LibCore/Directory.h>
+#include <LibCore/EventLoop.h>
+#include <LibCore/StandardPaths.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibGfx/SystemTheme.h>
+#include <LibMain/Main.h>
+#include <LibURL/Parser.h>
+#include <LibWeb/UIEvents/InputEvent.h>
+#include <LibWebView/Application.h>
+#include <LibWebView/HeadlessWebView.h>
+#include <LibWebView/Utilities.h>
+#include <stdlib.h>
+
+namespace {
+
+class TestApplication : public WebView::Application {
+ WEB_VIEW_APPLICATION(TestApplication)
+
+public:
+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)
+ : WebView::Application(move(ladybird_binary_path))
+ {
+ }
+
+ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions& web_content_options) override
+ {
+ browser_options.headless_mode = WebView::HeadlessMode::Test;
+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;
+ web_content_options.is_test_mode = WebView::IsTestMode::Yes;
+ }
+
+ virtual bool should_coordinate_browser_process() const override { return false; }
+};
+
+void click(WebView::ViewImplementation& view)
+{
+ view.enqueue_input_event(Web::MouseEvent {
+ .type = Web::MouseEvent::Type::MouseDown,
+ .position = { 10, 10 },
+ .screen_position = { 10, 10 },
+ .button = Web::UIEvents::MouseButton::Primary,
+ .buttons = Web::UIEvents::MouseButton::Primary,
+ .click_count = 1,
+ .browser_data = nullptr,
+ });
+ view.enqueue_input_event(Web::MouseEvent {
+ .type = Web::MouseEvent::Type::MouseUp,
+ .position = { 10, 10 },
+ .screen_position = { 10, 10 },
+ .button = Web::UIEvents::MouseButton::Primary,
+ .buttons = Web::UIEvents::MouseButton::None,
+ .click_count = 1,
+ .browser_data = nullptr,
+ });
+}
+
+}
+
+ErrorOr<int> ladybird_main(Main::Arguments arguments)
+{
+ auto test_config_directory = ByteString::formatted("{}/Ladybird-TestBeforeUnload-{}", Core::StandardPaths::tempfile_directory(), generate_random_uuid());
+ TRY(Core::Directory::create(test_config_directory, Core::Directory::CreateDirectories::Yes));
+ auto cleanup_test_config_directory = ScopeGuard([&] {
+ MUST(FileSystem::remove(test_config_directory, FileSystem::RecursionMode::Allowed));
+ });
+ VERIFY(setenv("XDG_CONFIG_HOME", test_config_directory.characters(), 1) == 0);
+
+#if defined(LADYBIRD_BINARY_PATH)
+ auto app = TRY(TestApplication::create(arguments, LADYBIRD_BINARY_PATH));
+#else
+ auto app = TRY(TestApplication::create(arguments, OptionalNone {}));
+#endif
+
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ auto theme = TRY(Gfx::load_system_theme(theme_path.string()));
+ auto view = WebView::HeadlessWebView::create(move(theme), { 800, 600 });
+
+ size_t loads_finished = 0;
+ view->on_load_finish = [&](auto const&) { ++loads_finished; };
+ Core::EventLoop::current().spin_until([&] { return loads_finished == 1; });
+
+ auto source_url = URL::Parser::basic_parse("data:text/html,<title>source</title><button style='width:100px;height:100px' onclick=\"document.title='activated'\">Activate</button><script>onbeforeunload=e=>e.preventDefault()</script>"sv).release_value();
+ auto destination_url = URL::Parser::basic_parse("data:text/html,<title>destination</title>Destination"sv).release_value();
+
+ auto view_is_at = [&](URL::URL const& url) { return view->url().serialize() == url.serialize(); };
+ auto load_and_wait = [&](URL::URL const& url) {
+ auto expected_loads_finished = loads_finished + 1;
+ view->load(url);
+ Core::EventLoop::current().spin_until([&] { return loads_finished >= expected_loads_finished && view_is_at(url); });
+ };
+ auto activate_page = [&] {
+ bool activated = false;
+ view->on_title_change = [&](auto const& title) { activated = title == "activated"sv; };
+ click(*view);
+ Core::EventLoop::current().spin_until([&] { return activated; });
+ view->on_title_change = {};
+ };
+
+ // Frontends without a beforeunload handler must act as if the user chose Leave.
+ load_and_wait(source_url);
+ activate_page();
+ load_and_wait(destination_url);
+
+ size_t prompt_count = 0;
+ bool accept_prompt = false;
+ Optional<String> prompt_source;
+ view->on_request_before_unload = [&](auto const& source, auto on_complete) {
+ ++prompt_count;
+ prompt_source = source;
+ on_complete(accept_prompt);
+ };
+
+ // A cancellation request without sticky activation must not show a prompt.
+ load_and_wait(source_url);
+ load_and_wait(destination_url);
+ VERIFY(prompt_count == 0);
+
+ // Stay cancels the navigation. The opaque data: origin uses the scheme fallback.
+ load_and_wait(source_url);
+ activate_page();
+ auto loads_finished_before_cancellation = loads_finished;
+ view->load(destination_url);
+ Core::EventLoop::current().spin_until([&] { return loads_finished > loads_finished_before_cancellation; });
+ VERIFY(prompt_count == 1);
+ VERIFY(prompt_source == "data://"sv);
+ VERIFY(view_is_at(source_url));
+
+ // A subsequent navigation may ask once again, and Leave allows it to proceed.
+ accept_prompt = true;
+ load_and_wait(destination_url);
+ VERIFY(prompt_count == 2);
+
+ outln("PASS: beforeunload prompt handling");
+ return 0;
+}