From 07928129dd62fc8478fd1e9967efe4cd16909340 Mon Sep 17 00:00:00 2001 From: Aliaksandr Kalenik Date: Sat, 30 Dec 2023 15:45:10 +0100 Subject: [PATCH] LibWeb: Wait until new document becomes active before running scripts Fixes https://github.com/SerenityOS/serenity/issues/22485 With this change WebContent does not crash when `location.reload()` is invoked but `Navigable::reload()` still not working because of spec issue (https://github.com/whatwg/html/issues/9869) so we can't add a test yet. --- Userland/Libraries/LibWeb/DOM/Document.cpp | 3 ++- Userland/Libraries/LibWeb/DOM/Document.h | 5 +++++ Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp | 6 ++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index c86a53780e..4b70f917fc 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -3628,7 +3628,8 @@ void Document::update_for_history_step_application(JS::NonnullGCPtr m_pending_animation_event_queue; bool m_needs_to_call_page_did_load { false }; + + // https://html.spec.whatwg.org/multipage/browsing-the-web.html#scripts-may-run-for-the-newly-created-document + bool m_ready_to_run_scripts { false }; }; template<> diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp index 82db4cbc93..b88ccca90b 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp @@ -2729,6 +2729,12 @@ void HTMLParser::handle_text(HTMLToken& token) // -> An end tag whose tag name is "script" if (token.is_end_tag() && token.tag_name() == HTML::TagNames::script) { + // https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-html + // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document. + if (!m_document->ready_to_run_scripts()) { + main_thread_event_loop().spin_until([&] { return m_document->ready_to_run_scripts(); }); + } + // FIXME: If the active speculative HTML parser is null and the JavaScript execution context stack is empty, then perform a microtask checkpoint. // Non-standard: Make sure the