A lot of web pages try to make you don't exit them by using the beforeUnload event on JS. Facebook, for instance, will show a warning if you try to use back / forward button , as the image below shows :
To avoid this i always used the code below to 'unbind' the event :
window.onbeforeunload = null;
But this is not working anymore. Even after running the code below, the warning message will still shows if i try to leave the page.
How to really get rid of these messages in a web application ? Facebook is only an example, i'm trying to do this using JS for study purposes.
The event is probably being registered via addEventListener rather than onbeforeunload. You could try adding a new event listener that overrides the previous one.
window.addEventListener("beforeunload", (event) => {
event.stopImmediatePropagation();
}, true);
The third parameter being true causes the event to go all the way down, so any other listeners will be prevented.
Related
I'm trying to close the browser after I have reached a order confirmation page and it throws a alert as shown below. This creates a misconception to user that his changes are unsaved. So I want to avoid this pop up.
I know this alert is triggered because of beforeunload event.
Solution that I have tried:
window.addEventListener("beforeunload",(event)=>{
return null;
})
and
window.onbeforeunload=null;
I'm not using jQuery in my application. Is there any other way that I can disable this event from firing.
Links that I have tried:
How to disable/override "Do you want to leave this site?" alert?
Disable "Changes you made may not be saved" pop-up window
How to disable "Changes you made may not be saved." dialog box (Chrome)?
None of them are working for me.
How can I achieve this without jQuery?. What I'm confused about is how to handle this event so that it doesn't show the pop up.
I'm using Chrome Version 101.0.4951.64
This could be due to some third-party library or other functionality in your code that listens for the "beforeunload" event and perhaps modifies the value of event.returnValue.
This workaround may work for you.
window.addEventListener('beforeunload', function (event) {
event.stopImmediatePropagation();
});
This will prevent the execution of the other listeners in the chain.
It is important to include this code at the top of the app to ensure that your function is executed first.
In the case of Angular, a good place can be in the ngOnInit of the AppComponent.
Check here.
Just adding a MDN documentation of beforeunload event for reference.
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload.
Internet Explorer does not respect the null return value and will display this to users as "null" text. You have to use undefined to skip the prompt.
I'm trying to use "pushState" and the "popstate" event to trap Back button navigation, however, while the popstate event triggers correctly in Firefox, it doesn't trigger in Chrome (Version 76.0.3809.87 (Official Build) (64-bit)) if there is no user interaction.
From testing, it looks like the popstate event only gets triggered if the user interacts with the page (ie. clicks somewhere on the document). So if you load the page without interacting and hit Back, the popstate function is not called.
I've added a Fiddle to showcase this: https://jsfiddle.net/0xwvLndu/
To test the Fiddle in Chrome, just click the link and hit the Back button. You'll see no alert. Then click the link again but this time click anywhere on the Fiddle document and then hit the Back button, the alert is then triggered.
I found a discussion on the Chromium forum that may relate to this quirk, and perhaps this has been implemented to prevent abuse of history entries - https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/OCS7g72HtyI and https://github.com/WICG/interventions/issues/21#issuecomment-425609246
If this is the case, does it mean that popstate cannot be relied on anymore to trap Back button actions, and if so, is there a work around solution?
Below is an example of what I've been testing with:
window.addEventListener('load', function() {
history.pushState(null, null, document.URL);
});
window.addEventListener('popstate', function(event) {
alert('test');
});
I expected the alert to be triggered on Back Button regardless of user interaction, but this does not happen in Chrome.
Try adding a setTimeout of 0
window.onpopstate = () => setTimeout(alert.bind(window, "Pop"), 0);
When writing functions that process popstate event it is important to take into account that properties like window.location will already reflect the state change (if it affected the current URL), but document might still not. If the goal is to catch the moment when the new document state is already fully in place, a zero-delay setTimeout() method call should be used to effectively put its inner callback function that does the processing at the end of the browser event loop: window.onpopstate = () => setTimeout(doSomeThing, 0);
Content is taken from
https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event
On a sidenote it is advised not to use this as browsers may remove this any time.
As others suggested in comment, this should be by design of browser software to prevent hijacking of its default back button behavior.
I have an HTML page that includes only a script tag, I don't control the script and I can't change it (so I can't fire my custom event for example).
The script ends with a redirect (using window.location).
Is there a way to add a new script to the page that will listen to the page events and "catch" the redirect (actually it's better for me to catch the new loaded document)?
Something like:
window.addEventListener('redirected', function() {
// do staff
});
(I know there is no "redirected" event, it's just for the example).
It's very important to make it clear that the redirect isn't caused by an anchor click or back/forward button click, so I can't use events like click or popstate.
You might want to look at the onpagehide event or the onunload event, both of which occur when the user navigates away from the page.
However, if you wish to interfere or prevent the redirection itself, onbeforeunload is what you want.
Just take a look at :
unload function w3school or mozilla developper network
beacon function for sending a final XMLHttpRequest
(Note: FireFox only)
The Back-Forward cache is a caching system in firefox that runs when the back button is clicked. It will then simply use the DOM from the previous page that is in it's cache instead of reloading the entire page (and re-requesting files).
I'm using piwik (an analytics service), that requires a tracking code snippet to be added to the footer. Upon adding this, the back-forward cache no longer works.
It is my understanding that, if there is an unload event (or beforeunload) the bfcache is automatically disabled. This is likely what is happening here.
Is there anything I can add to make the BFCache work anyway?
To make matters worse, I cannot add any custom code below the piwik code. That one is always last.
I added the code displayed below to try and remove any unload events that are registered, but the BFcache is still not working.
$(window).unbind('beforeunload');
$(window).unbind('unload');
window.onbeforeunload = null;
window.onunload = null;
I also tried:
function UnloadHandler() {
window.removeEventListener('unload', UnloadHandler, false);
}
window.addEventListener('unload', UnloadHandler, false);
$(window).unload(function () { $(window).unbind('unload'); });
but this too does not work.
I have placed some samples online. Remember to test this with Firefox:
this one shows a working BFcache (you will get an different alert based on whether or not the back button was clicked)
http://users.telenet.be/prullen/bfcache/a.html
Loaded piwik, BFCache no longer works
http://users.telenet.be/prullen/bfcache/b.html
Loaded piwik, tried to unset onload event, but still not working
http://users.telenet.be/prullen/bfcache/c.html
Using unloadhandler
http://users.telenet.be/prullen/bfcache/d.html
Suggestions by #roasted
http://users.telenet.be/prullen/bfcache/e.html
http://users.telenet.be/prullen/bfcache/f.html
More information about BFCache:
https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching
You can see another demo of the behavior here:
http://www.twmagic.com/misc/cache.html
If you add dom elements, and click the first link, then return - the dom elements are still there. However, if you add an onload or beforeunload event that is not the case. Again, test this in firefox.
Any ideas?
In order to enable BFCache you need to remove beforeunload event listener. It should be the same listener which was added by Piwik code, otherwise removeEventListener will do nothing.
That listener is unreachable outside of the Piwik's source, so one does not simply remove it.
But, if you have a possibility to insert code before the Piwik, you can try to override addEventListener, track added handlers and expose function to remove all tracked handlers at once.
I need to control over back button. I checked similar posts it wont work as i expect.
I need to show custom confirmation message on back button clicked. If uses clicks 'Cancel', then they should stay on the same page.
Can anyone has ready sample code?
Thanks
Since the back button is part of the browser's functionality, not the web page's, the best you can do is handle the beforeunload event. This lets you provide a custom cancel message before the user leaves the page for any reason. Some intelligence about how you set up the handler and adding additional handlers to remove the beforeunload handler before taking links, etc. that should legitimately take the user to a different page can approximate the behavior you are looking for. See the example on the referenced documentation:
window.addEventListener("beforeunload", function( event ) {
event.returnValue = "a non-empty string";
}, false);
Use the
onbeforeunload
event instead. It'll triggered before user leaves the page.
Code example:
window.addEventListener('beforeunload',function(e){
!confirm('Do you want to leave?') && e.preventDefault();
},false);