Use beforeunload only on tab close - javascript

below code will trigger a popup with Reload site? or Leave site? message
on page refresh, press back button or on tab close
How to trigger this event only on tab close
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});

There is no direct way of doing it because javascript doesen't have access to read browser actions. But if you want to do something on the server based on these actions, you may find this helpful.

Related

Know status of windows.beforeunload event by user

I am using windows.beforeunload event to prompt user whether they would like to unsaved changes or not.
Inside windows.beforeunload event, I want to know status whether user clicked on "Leave" button or "Cancel" button (In Chrome). Is it possible? If not then any alternate solution?
Per MDN beforeunload
This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.
The above implies that the event is cancelable, but...
According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.
And even then, if you are indeed doing that...
To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.
Proper Use Case
However, unlike the unload event, there is a legitimate use case for the beforeunload event: the scenario where the user has entered unsaved data that will be lost if the page is unloaded.
It is recommended that developers listen for beforeunload only in this scenario, and only when they actually have unsaved changes, so as to minimize the effect on performance. See the Examples section below for an example of this.
See the Page Lifecycle API guide for more information about the problems associated with the beforeunload event.
Example
In this example a page listens for changes to a text input. If the element contains a value, it adds a listener for beforeunload. If the element is empty, it removes the listener:
const beforeUnloadListener = (event) => {
event.preventDefault();
return event.returnValue = "Are you sure you want to exit?";
};
const nameInput = document.querySelector("#name");
nameInput.addEventListener("input", (event) => {
if (event.target.value !== "") {
addEventListener("beforeunload", beforeUnloadListener, {capture: true});
} else {
removeEventListener("beforeunload", beforeUnloadListener, {capture: true});
}
});

how to skip confirm pop up on beforeunload and show my own bootstrap modal?

I want to skip the default pop up which will come on beforeunload event and want to show my own modal which is asking the user to give feedback on browser/tab close. In that modal if user click "OK" then I want to redirect the user to my feedback page and if the user clicks "NO" then the particular tab should close. Is there a way to do this?
As you can read here: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload you may change the event.returnValue of the beforeunload event to a custom string. Like this:
window.addEventListener("beforeunload", function( event ) {
event.returnValue = "Don't leave!";
});
This will open a confirm dialog when the user is leaving the current page.
You may open your modal window in this event, but this will not stop the user form leaving, so new content will not be seen.
Of course the unload event can not be canceled (https://developer.mozilla.org/en-US/docs/Web/Events/unload) and UI interactions are ineffective (window.open, alert, confirm etc.)
So i think the closest you can get it this: http://jsfiddle.net/s6qWr/
var $modal = document.getElementById("modal");
window.addEventListener("beforeunload", function(event){
$modal.classList.add("visible");
event.returnValue = "Please tell us about your experience";
});

window.onunload event not firing

I have a silverlight application in which I need to fire signout event if user navigates away.
I have tried a sample function as
window.onunload = function test() { alert("test"); }
The problem is when I navigate away from the webpage the event fires, but I need this event to fire when user closed browser or tab.
In my case it was not necessary that the page prompts user if he is sure he wants to exit. So I called my signout method inside the 'window.onbeforeunload' event(also flashed a message box to so that webservice gets enough time to successfully signout).
Also used
document.onbeforeunload = undefined;
inside my 'window.onbeforeunload' event to avoid the confirmation window.

Event to be triggered when leaving website or closes the browser

I´m trying for a while execute a JavaScript function when a user leaves web site by typing a address in the browser and hits return or the user closes the browser clicking in the x button.
I tried the unload event but I cannot get the alert.
This is what I am doing:
$(window).unload(function () {
alert("Are you sure?");
});
also
$(body).unload(function () {
alert("Are you sure?");
});
I am running out of ideas!
You can listen to beforeunload event that fires before the unload event, when the page is unloaded.
$(window).on('beforeunload', function(){
// ...
})
Some browsers (like Chrome) block alerts in unload event handlers, to prevent exactly these kind of annoying messages. Try a console.log or put a breakpoint in to find out if the handler is triggered when you don't have an alert there.
SO question on a similar line:
window.onunload is not working properly in Chrome browser. Can any one help me?
You can only pass the alert by returning a string in a beforeunload handler (HT #undefined), but I would avoid even that, because popups are generally bad, and most people will do minimum processing to work out the make-this-thing-go-away option before they actually think about the contents of the box.
The function you defined in window.onbeforeunload if it returns a string it will pop up a confirm navigation prompt with that message.
Alerts may be ignored!
window.onbeforeunload = function() {
return "All unsaved data will be lost. Are you sure?";
};
Some browsers handle the onbeforeunload differently. Recent Firefox for example will ignore your return string and just display a standard message.
$(window).bind('beforeunload', function(){
alert("Are your sure?")
});

Link to anchor (ajax url) doesn't call onBeforeUnload

I have an onbeforeunload event :
$().ready(function() {
window.onbeforeunload=function() { return "haha" };
});
And my links are like this (ajax web site) :
<a href="#pageX" />
But the onbeforeunload is never called. What can i do ?
Thanks
I'm guessing since you're trying to bind to the onbeforeunload and return a string, that you're looking to provide the user with an "Are you sure you want to leave this page" dialog on an AJAX site.
In which case you probably need to go about this a little differently by binding a click handler onto the links. So you can prevent the hash change until the confirmation is made.
Something like:
$('a[href^="#"]').live('click',function(e){
if( //should we be confirming first? ) {
//put your confirmation code here either using default JS windows or your own CSS/jQueryUI dialog boxes
// this code should either cache the url of the link that was clicked and manually update the location with it when the user confirms the dialog box (if you're using JQUI windows) or simply use JS confirmation boxes and based on the response, all you need to do is return; and the link click will handle normally
e.preventDefault(); //prevent the link from changing the hash tag just yet
e.stopImmediatePropagation(); //prevent any parent elements from firing any events for this click
}
} );
Don't get me wrong, but are you serious ?
That link just refers a hash-tag, hence, it will not leave the current site and there will be no call to onbeforeunload nor unload.
If there is any *click event handlerbound to that anchor aswell, there must be something in the event handler code which really forces the current site to get unloaded (location.href` for instance).
If you just switch HTML via Ajax, there is no onbeforeunload aswell.
You could bind a handler to the onhashchange event (check browser compatibilty) but that would fire for any change that happens in your url/hash.
You're probably looking for the onhashchange event:
https://developer.mozilla.org/en/DOM/window.onhashchange

Categories

Resources