From 0f6a5c5fc24e8dc9125c5c536c8547a86ca87b15 Mon Sep 17 00:00:00 2001 From: Colin Ihrig Date: Tue, 28 Jun 2022 10:49:30 -0400 Subject: feat(web): add beforeunload event (#14830) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit adds the 'beforeunload' event. Co-authored-by: Bartek IwaƄczuk --- runtime/js/99_main.js | 1 + runtime/worker.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) (limited to 'runtime') diff --git a/runtime/js/99_main.js b/runtime/js/99_main.js index 1d046d161..c13faa936 100644 --- a/runtime/js/99_main.js +++ b/runtime/js/99_main.js @@ -583,6 +583,7 @@ delete Intl.v8BreakIterator; defineEventHandler(window, "error"); defineEventHandler(window, "load"); + defineEventHandler(window, "beforeunload"); defineEventHandler(window, "unload"); const isUnloadDispatched = SymbolFor("isUnloadDispatched"); // Stores the flag for checking whether unload is dispatched or not. diff --git a/runtime/worker.rs b/runtime/worker.rs index acb50dc30..fd937559f 100644 --- a/runtime/worker.rs +++ b/runtime/worker.rs @@ -371,6 +371,24 @@ impl MainWorker { "dispatchEvent(new Event('unload'))", ) } + + /// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean + /// indicating if the event was prevented and thus event loop should continue + /// running. + pub fn dispatch_beforeunload_event( + &mut self, + script_name: &str, + ) -> Result { + let value = self.js_runtime.execute_script( + script_name, + // NOTE(@bartlomieju): not using `globalThis` here, because user might delete + // it. Instead we're using global `dispatchEvent` function which will + // used a saved reference to global scope. + "dispatchEvent(new Event('beforeunload', { cancelable: true }));", + )?; + let local_value = value.open(&mut self.js_runtime.handle_scope()); + Ok(local_value.is_false()) + } } #[cfg(test)] -- cgit v1.2.3