From ee8a1a9b3fc8f1b50be7016c59733d4bb288ea9f Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 19 Sep 2021 15:02:04 +0200 Subject: [PATCH] LibWeb: Keep XMLHttpRequest alive while handling load/error events A weakly held XHR object is not guaranteed to remain alive after running arbitrary JavaScript, so let's make sure we take a strong reference in the ResourceLoader callbacks here. --- Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp index 0cc462d59b..d211d221a8 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp @@ -212,7 +212,8 @@ DOM::ExceptionOr XMLHttpRequest::send() ResourceLoader::the().load( request, [weak_this = make_weak_ptr()](auto data, auto& response_headers, auto status_code) { - if (!weak_this) + auto strong_this = weak_this.strong_ref(); + if (!strong_this) return; auto& xhr = const_cast(*weak_this); // FIXME: Handle OOM failure. @@ -235,12 +236,14 @@ DOM::ExceptionOr XMLHttpRequest::send() xhr.fire_progress_event(EventNames::loadend, transmitted, length); }, [weak_this = make_weak_ptr()](auto& error, auto status_code) { - if (!weak_this) - return; dbgln("XHR failed to load: {}", error); - const_cast(*weak_this).set_ready_state(ReadyState::Done); - const_cast(*weak_this).set_status(status_code.value_or(0)); - const_cast(*weak_this).dispatch_event(DOM::Event::create(HTML::EventNames::error)); + auto strong_this = weak_this.strong_ref(); + if (!strong_this) + return; + auto& xhr = const_cast(*strong_this); + xhr.set_ready_state(ReadyState::Done); + xhr.set_status(status_code.value_or(0)); + xhr.dispatch_event(DOM::Event::create(HTML::EventNames::error)); }); } else { TODO();