JavaScript set onbeforeunload to default | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

JavaScript set onbeforeunload to default

In my web game, I want to use onbeforeunload function to alert users that their game won't be saved. But when they click on the leave button, I don't want to show them this again, so I want to set onbeforeunload to default function without alertbox. What should I do?

20th May 2020, 3:45 PM
Dominik Vladař
Dominik Vladař - avatar
5 Answers
+ 10
Jakob Meier document.body.onbeforeunload = function (){ return false; }; function clicked_leaving(){ /*I want to prevent alert here*/ }
26th May 2020, 6:35 AM
Dominik Vladař
Dominik Vladař - avatar
+ 10
Jakob Meier thank you so much👍
26th May 2020, 6:56 AM
Dominik Vladař
Dominik Vladař - avatar
+ 2
Implements something like an "once decorator" pattern with closures to abstract behaviour in any part of code... const once = (fn, ctx=null, ...args) => { let visited = !1; return (event) => { if (visited) { event.preventDefault(); return; } // in other case, invoke! visited = !0; return fn.apply(ctx, [event, ...args]); }; }; You can also remove the listener as part of execution: https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent window.addEventListener("beforeunload", function handler(event) { // Cancel the event as stated by the standard. event.preventDefault(); // Older browsers supported custom message event.returnValue = 'You have unsaved work. Continue?'; // do more work above... }, { // auto unregister after execute once: true });
26th Jan 2021, 12:39 PM
David Ordás
David Ordás - avatar
+ 1
you could declare a variable like seen_alert = false and if they are shown the alert it is being set to true and then you check in your onbeforeunload if(seen_alert){ //don't show alert } else { //show_alert seen_alert=true } Maybe you could publish the piece of code this is about, for me to understand it better
26th May 2020, 5:57 AM
Jakob Meier
Jakob Meier - avatar
+ 1
yeah you could totally do: var leaving = false; and then in your unload event I think you do document.body.onbeforeunload = function (event) { if(leaving) { //save game //don't show alert } else { //game not saved event.preventDefault(); //show alert } }
26th May 2020, 6:52 AM
Jakob Meier
Jakob Meier - avatar