var inFormOrLink;
$('a').on('click', function () { inFormOrLink = true; });
$('form').on('submit', function () { inFormOrLink = true; });
$(window).on('beforeunload', function (eventObject) {
var returnValue = undefined;
if (!inFormOrLink) {
returnValue = "Do you really want to close?";
}
if (returnValue != undefined) {
eventObject.returnValue = returnValue;
return returnValue;
}
});
Ref : Browser close event
I tried to execute the above mentioned code in Chrome Version 65.0.3325.181
it is working properly i.e popup does not open while redirecting or submitting form,
i want to show popup only when user close the tab, sometimes browser shows the popup but sometimes tab gets closed without showing popup.
I don't know why it is happening.
I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload and onunload methods are also not working.
How do I detect the window close, unload, or beforeunload events?
Have you tried this code?
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(function () {
$("a").not('#lnkLogOut').click(function () {
window.onbeforeunload = null;
});
$(".btn").click(function () {
window.onbeforeunload = null;
});
});
The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.
One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.
Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.
The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
var prevKey="";
$(document).keydown(function (e) {
if (e.key=="F5") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
window.onbeforeunload = ConfirmLeave;
}
prevKey = e.key.toUpperCase();
});
The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().
Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return confirm("Do you really want to close?");
});
});
For simple follow following steps:
open http://jsfiddle.net/
enter something into html, css or javascript box
try to close tab in chrome
It should show following picture:
Hi i got a tricky solution, which works only on new browsers:
just open a websocket to your server, when the user closes the window, the onclose event will be fired
Following script will give message on Chrome and IE:
<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here
return "Please click 'Stay on this Page' and we will give you candy";
};
</script>
Chrome
IE
on Firefox you will get generic message
Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.
Response to question in comment
F5 will fire event again, so will Atl+F4.
As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return "Do you really want to close?";
});
});
more details can be found at : developer.mozilla.org
jQuery .bind() has been deprecated. Use .on() instead
$(window).on("beforeunload", function() {
runBeforeClose();
});
Maybe it's better to use the path detecting mouse.
In BrowserClosureNotice you have a demo example and pure javascript library to do it.
It isn't perfect, but avoid problems of document or mouse events...
<script type="text/javascript">
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
</script>
Please try this code, this is working fine for me. This custom message is coming into Chrome browser but in Mozilla this message is not showing.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
var ref="load";
$.ajax({
type: 'get',
async: false,
url: 'logout.php',
data:
{
ref:ref
},
success:function(data)
{
console.log(data);
}
});
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
This is used for when logged in user close the browser or browser tab it will automatically logout the user account...
You can try something like this.
<html>
<head>
<title>test</title>
<script>
function openChecking(){
// alert("open");
var width = Number(screen.width-(screen.width*0.25));
var height = Number(screen.height-(screen.height*0.25));
var leftscr = Number((screen.width/2)-(width/2)); // center the window
var topscr = Number((screen.height/2)-(height/2));
var url = "";
var title = 'popup';
var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
var popup = window.open(url, title, properties);
var crono = window.setInterval(function() {
if (popup.closed !== false) { // !== opera compatibility reasons
window.clearInterval(crono);
checkClosed();
}
}, 250); //we check if the window is closed every 1/4 second
}
function checkClosed(){
alert("closed!!");
// do something
}
</script>
</head>
<body>
<button onclick="openChecking()">Click Me</button>
</body>
</html>
When the user closes the window, the callback will be fired.
I've come across a nasty website that managed to refresh the page every time I tried to close the tab. Basically you couldn't close that page. I got around it by disabling javascript on that page.
How do they do it?
I've tried location.replace inside onbeforeunload and it doesn't work:
window.onbeforeunload = function(e) {
window.location.replace(window.location.href);
};
Here is the source of the page in question, where I don't get how they do it:
<script type="text/javascript">
function c(b)
{
document.write(b);
}
function wrapped3(d)
{
return d.replace(/(.)(.)/g, '%$1$2');
}
function wrapped(b)
{
var tmp = window['decodeURI' + 'Component'];
return tmp(wrapped3(b))
}
function show_page(a)
{
c(wrapped(a)
.split('{{addr}}').join('//ip')
.split('{{country}}').join('Great Britain')
.split('{{region}}').join('London, City of')
.split('{{city}}').join('London')
.split('{{ltude}}').join('//latitude')
.split('{{referrer}}').join('//url here')
);
}
show_page('//long string here');
</script>
window.onbeforeunload is the correct solution, here is an example:
var popit = true;
window.onbeforeunload = function() {
if(popit == true) {
popit = false;
return "Are you sure you want to leave?";
}
}
http://jsfiddle.net/SQAmG/3/
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.
I am working on asp.net(c#).I try to add a javascript alert when a user tries to close the current tab in browser. The code is not working in Chrome.Please can any one help about this topic.
This is my code:
<script type="text/javascript">
window.onbeforeunload = function close_window() {
var r = confirm("Do you want to view other topics?");
if (r == true)
{
alert("You pressed OK!");
var Url = "http://stackoverflow.com/";
window.location = Url;
return false;
}
else
{
window.close();
}
}
Remove the () when you're calling the function.
It should be:
window.onbeforeunload = function close_window {
Actually, try this.
function close_window() {
...
}
window.onbeforeunload = close_window;
And yes--it's really bad practice.