Javascript leaving the page event occurs. JavaScript - Window Object: Opening and closing windows. Window object methods: open(), close(), print(), focus() and blur()



window js events (14)

I want to capture the browser window/tab close event. I tried the following with jQuery:

JQuery(window).bind("beforeunload", function() ( return confirm("Do you really want to close?") ))

But it also works with form submission, which is not what I want. I want an event that only fires when the user closes the window.

As of jQuery 1.7, the .live() method has been deprecated. Use .on() to attach event handlers. Older users jQuery versions should use .delegate() in preference to .live()

$(window).bind("beforeunload", function() ( return true || confirm("Do you really want to close?"); ));

$(window).unbind();

JQuery(window).bind("beforeunload", function (e) ( var activeElementTagName = e.target.activeElement.tagName; if (activeElementTagName != "A" && activeElementTagName != "INPUT") ( return "Do you really want to close?"; ) ))

My answer is aimed at providing simple tests.

HOW

See @SLaks answer.

$(window).on("beforeunload", function() ( return inFormOrLink ? "Do you really want to close?" : null; ))

How long will it take for the browser to finally close the page?

Whenever the user closes the page (x button or CTRL + W), the browser executes this code before beforeunload , but not indefinitely. The only exception is the confirmation window (return "Do you really want to close?"), which will wait for the user's response.

Chrome: 2 seconds.
Firefox: ∞ (or double click or force close)
Edge: ∞ (or double click)
Explorer 11: 0 seconds.
Safari: TODO

What we used to test this:

  • Node.js Express server with request log
  • The following short HTML file

What it does is send as many requests as possible before the browser completes its page (synchronously).

function request() ( return $.ajax(( type: "GET", url: "http://localhost:3030/" + Date.now(), async: true )).responseText; ) window.onbeforeunload = ( ) => ( while (true) ( ​​request(); ) return null; )

Chrome Output:

GET /1480451321041 404 0.389 ms - 32 GET /1480451321052 404 0.219 ms - 32 ... GET /hello/1480451322998 404 0.328 ms - 32 1957ms ≈ 2 seconds // we assume it"s 2 seconds since requests can take a few milliseconds to be sent.

Try this also

Window.onbeforeunload = function () ( if (pasteEditorChange) ( var btn = confirm("Do You Want to Save the Changess?"); if(btn === true)( SavetoEdit();//your function call ) else ( windowClose();//your function call ) ) else ( windowClose();//your function call ) );

Just check...

Function wopen_close())( var w = window.open($url, "_blank", "width=600, height=400, scrollbars=no, status=no, resizable=no, screenx=0, screeny=0"); w.onunload = function() ( if (window.closed) ( alert("window closed"); )else( alert("just refreshed"); ) ) )

Unfortunately, whether a reload, a new page redirect, or a browser close event will be triggered. The alternative is to catch the id that fires the event, and if it's a form, don't call any function, and if it's not the form id, then do what you want to do when the page closes. I'm not sure if this is also possible directly and is tedious.

There are some little things you can do before the client closes the tab. javascript detects browser close tab/close browser, but if your list of actions is large and the tab closes before it's completed, you're helpless. You can try, but with my experience it doesn't depend on it.

Window.addEventListener("beforeunload", function (e) ( var confirmationMessage = "\o/"; /* Do you small action code here */ (e || window.event).returnValue = confirmationMessage; //Gecko + IE return confirmationMessage; //Webkit, Safari, Chrome ));

If your form view is sending them to another page (which I believe it is, i.e. running beforeunload), you could try changing the form's beforeunload to an ajax call. This way they won't leave your page when the form is beforeunloaded, and you can use your beforeunload bindings as you wish.

For a solution that worked well with 3rd party controls like Telerik (like RadComboBox) and DevExpress, which use Anchor tags for various reasons, consider the following code, which is a slightly improved version of the desm code with a better selector for itself anchor tag binding :

Var inFormOrLink; $("a:not(), a").live("click", function() ( inFormOrLink = true; )); $("form").bind("submit", function() ( inFormOrLink = true; )); $(window).bind("beforeunload", function(eventObject) ( var returnValue = undefined; if (! inFormOrLink) ( returnValue = "Do you really want to close?"; } eventObject.returnValue = returnValue; return returnValue; });!}

I used Slaks but it doesn't work as is because the onbeforeunload returnValue is parsed as a string and then displayed in the browser confirmation window. This is how it is displayed true, for example "true".

Just using feedback. Here is my code

Var preventUnloadPrompt; var messageBeforeUnload = "my message here - Are you sure you want to leave this page?"; //var redirectAfterPrompt = "http://www.google.co.in"; $("a").live("click", function() ( preventUnloadPrompt = true; )); $("form").live("submit", function() ( preventUnloadPrompt = true; )); $(window).bind("beforeunload", function(e) ( var rval; if(preventUnloadPrompt) ( return; ) else ( //location.replace(redirectAfterPrompt); return messageBeforeUnload; ) return rval; ))

Var validNavigation = false; jQuery(document).ready(function () ( wireUpEvents(); )); 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 () ( debugger if (!validNavigation) ( endSession(); ) ) // Attach the event keypress to exclude the F5 refresh $(document).bind("keypress", function (e) ( debugger if (e.keyCode == 116) ( validNavigation = true; ) )); // Attach the event click for all links in the page $("a").bind("click", function () ( debugger validNavigation = true; )); // Attach the event submit for all forms in the page $("form").bind( "submit", function () ( debugger validNavigation = true; )); // Attach the event click for all inputs in the page $("input").bind("click", function () ( debugger validNavigation = true; )); )`enter code here`

My problem: The "onbeforeunload" event will only be fired if there have been an odd number of submissions (clicks). I had a combination of solutions from similar threads on SO to get my solution to work. ok, my code will speak.

$(document).ready(function() ( updatefgallowPrompt(true); window.onbeforeunload = WarnUser; ) function WarnUser() ( var allowPrompt = getfgallowPrompt(); if(allowPrompt) ( saveIndexedDataAlert(); return null; ) else ( updatefgallowPrompt(true); event.stopPropagation ) ) function saveIndexedDataAlert() ( var allowPrompt = getfgallowPrompt(); var lenIndexedDocs = parseInt($("#sortable3 > li").size()) + parseInt($("#sortable3 > ul").size()); if(allowPrompt && $.trim(lenIndexedDocs) > 0) ( event.returnValue = "Your message"; } else { event.returnValue = " "; updatefgallowPrompt(true); } } $(document).click(function(event) { $("a").live("click", function() { updatefgallowPrompt(false); }); }); function updatefgallowPrompt (allowPrompt){ //exit msg dfds $("body").data("allowPrompt", allowPrompt); } function getfgallowPrompt(){ return $("body").data("allowPrompt"); }!}

Afterwards worked for me;

$(window).unload(function(event) ( if(event.clientY< 0) { //do whatever you want when closing the window.. } });

Window.onbeforeunload = function () ( return "Do you really want to close?"; );

Perhaps just a beforeunload event handler in the form's submit event handler:

JQuery("form").submit(function() ( jQuery(window).unbind("beforeunload"); ... ));

2

I have one parent page and a child page. child page opened in new tab

I want to show one warning message (child page closes) when I close the child tab.
How to show closed messgae when closing tab? (Not a refreshing time)

I used OnUnload and onbeforeunload .
The two methods are also called when refreshing the page and closing tabs.

Window.onunload = function doUnload(e) ( alert("Child window is closing..."); )

Window.onbeforeunload = function doUnload(e) ( alert("Child window is closing..."); )

I have to show the warning message, just close the tab in the browser.

Help me. Thanks in advance.

I'm using the following script. It worked in IE. But didn't work in FireFox

window.onbeforeunload = function() ( if ((window.event.clientX< 0) || (window.event.clientY < 0) || (window.event.clientX < -80)) { alert("Child window is closing..."); } };

How to achieve this in FireFox and other browser.

  • 4 answers
  • Sorting:

    Activity

1

For this afaik was never a cross browser scenario. The solution is to NOT rely on undocumented and variable browser-specific features to detect anything important.

Since you have a CHILD page, you can set up a test on the parent (opener) that checks the childWindowHandle.closed property at intervals and acts on that.

1

Assuming it just tries to fire the beforeunload Crossbrowser event, this pretty much does it (except in Opera)

Try( // http://www.opera.com/support/kb/view/827/ opera.setOverrideHistoryNavigationMode("compatible"); history.navigationMode = "compatible"; )catch(e)() //Our Where The F" Are You Going Message function ReturnMessage() ( return "WTF!!!"; ) //UnBind Function function UnBindWindow() ( window.onbeforeunload = null; return true; ) //Bind Links we dont want to affect document .getElementById("homebtn").onclick = UnBindWindow; document.getElementById("googlebtn").onclick = UnBindWindow; //Bind Exit Message Dialogue window.onbeforeunload = ReturnMessage;

0

You might not be able to do this except for some cookie based methods, which is a development workaround as it is not persistent cookies. The second identification of page refresh, form-based redirect or reverse redirect or browser close with event dumping is not straightforward and tedious. Recommend not to depend on this.

you can do some little things before the client closes the tab. javascript detect browser close tab/close browser , but if your action list is large and the tab closes before it's completed, you're helpless. You can try, but with my experience it doesn't depend on it. Yes, you cannot differentiate back, update and close at this time. Therefore, there is no reliable way to tell whether a child is truly closed.

Window.addEventListener("beforeunload", function (e) ( var confirmationMessage = "\o/"; /* Do you small action code here */ (e || window.event).returnValue = confirmationMessage; //Gecko + IE return confirmationMessage; //Webkit, Safari, Chrome ));



js page reload event (14)

I want to capture the browser window/tab close event. I tried the following with jQuery:

JQuery(window).bind("beforeunload", function() ( return confirm("Do you really want to close?") ))

But it also works with form submission, which is not what I want. I want an event that only fires when the user closes the window.

Perhaps just a beforeunload event handler in the form's submit event handler:

JQuery("form").submit(function() ( jQuery(window).unbind("beforeunload"); ... ));

If your form view is sending them to another page (which I believe it is, i.e. running beforeunload), you could try changing the form's beforeunload to an ajax call. This way they won't leave your page when the form is beforeunloaded, and you can use your beforeunload bindings as you wish.

Try this also

Window.onbeforeunload = function () ( if (pasteEditorChange) ( var btn = confirm("Do You Want to Save the Changess?"); if(btn === true)( SavetoEdit();//your function call ) else ( windowClose();//your function call ) ) else ( windowClose();//your function call ) );

Afterwards worked for me;

$(window).unload(function(event) ( if(event.clientY< 0) { //do whatever you want when closing the window.. } });

I used Slaks but it doesn't work as is because the onbeforeunload returnValue is parsed as a string and then displayed in the browser confirmation window. This is how the value true is displayed, for example "true".

Just using feedback. Here is my code

Var preventUnloadPrompt; var messageBeforeUnload = "my message here - Are you sure you want to leave this page?"; //var redirectAfterPrompt = "http://www.google.co.in"; $("a").live("click", function() ( preventUnloadPrompt = true; )); $("form").live("submit", function() ( preventUnloadPrompt = true; )); $(window).bind("beforeunload", function(e) ( var rval; if(preventUnloadPrompt) ( return; ) else ( //location.replace(redirectAfterPrompt); return messageBeforeUnload; ) return rval; ))

Var validNavigation = false; jQuery(document).ready(function () ( wireUpEvents(); )); 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 () ( debugger if (!validNavigation) ( endSession(); ) ) // Attach the event keypress to exclude the F5 refresh $(document).bind("keypress", function (e) ( debugger if (e.keyCode == 116) ( validNavigation = true; ) )); // Attach the event click for all links in the page $("a").bind("click", function () ( debugger validNavigation = true; )); // Attach the event submit for all forms in the page $("form").bind( "submit", function () ( debugger validNavigation = true; )); // Attach the event click for all inputs in the page $("input").bind("click", function () ( debugger validNavigation = true; )); )`enter code here`

Perhaps you can handle OnSubmit and set a flag that you later check in the OnBeforeUnload handler.

JQuery(window).bind("beforeunload", function (e) ( var activeElementTagName = e.target.activeElement.tagName; if (activeElementTagName != "A" && activeElementTagName != "INPUT") ( return "Do you really want to close?"; ) ))

For a solution that worked well with 3rd party controls like Telerik (like RadComboBox) and DevExpress, which use Anchor tags for various reasons, consider the following code, which is a slightly improved version of the desm code with a better selector for itself anchor tag binding :

Var inFormOrLink; $("a:not(), a").live("click", function() ( inFormOrLink = true; )); $("form").bind("submit", function() ( inFormOrLink = true; )); $(window).bind("beforeunload", function(eventObject) ( var returnValue = undefined; if (! inFormOrLink) ( returnValue = "Do you really want to close?"; } eventObject.returnValue = returnValue; return returnValue; });!}

My answer is aimed at providing simple tests.

HOW

See @SLaks answer.

$(window).on("beforeunload", function() ( return inFormOrLink ? "Do you really want to close?" : null; ))

How long will it take for the browser to finally close the page?

Whenever the user closes the page (x button or CTRL + W), the browser executes this code before beforeunload , but not indefinitely. The only exception is the confirmation window (return "Do you really want to close?"), which will wait for the user's response.

Chrome: 2 seconds.
Firefox: ∞ (or double click or force close)
Edge: ∞ (or double click)
Explorer 11: 0 seconds.
Safari: TODO

What we used to test this:

  • Node.js Express server with request log
  • The following short HTML file

What it does is send as many requests as possible before the browser completes its page (synchronously).

function request() ( return $.ajax(( type: "GET", url: "http://localhost:3030/" + Date.now(), async: true )).responseText; ) window.onbeforeunload = ( ) => ( while (true) ( ​​request(); ) return null; )

Chrome Output:

GET /1480451321041 404 0.389 ms - 32 GET /1480451321052 404 0.219 ms - 32 ... GET /hello/1480451322998 404 0.328 ms - 32 1957ms ≈ 2 seconds // we assume it"s 2 seconds since requests can take a few milliseconds to be sent.

For a cross-browser solution (tested in Chrome 21, IE9, FF15), consider the following code, which is a slightly modified version of the Slaks code:

Var inFormOrLink; $("a").live("click", function() ( inFormOrLink = true; )); $("form").bind("submit", function() ( inFormOrLink = true; )); $(window).bind("beforeunload", function(eventObject) ( var returnValue = undefined; if (! inFormOrLink) ( returnValue = "Do you really want to close?"; } eventObject.returnValue = returnValue; return returnValue; }); !}

Note that with Firefox 4 the message "Are you sure you want to close?" appears. not displayed. FF simply displays a general message. See note at https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

The beforeunload event fires whenever a user leaves your page for any reason.

For example, it will be triggered if the user submits a form, clicks a link, closes a window (or tab), or navigates to new page using the address bar, search box, or bookmark.

Var inFormOrLink; $("a").on("click", function() ( inFormOrLink = true; )); $("form").on("submit", function() ( inFormOrLink = true; )); $(window).on("beforeunload", function() ( return inFormOrLink ? "Do you really want to close?" : null; ))

For jQuery versions older than 1.7, try this:

Var inFormOrLink; $("a").live("click", function() ( inFormOrLink = true; )); $("form").bind("submit", function() ( inFormOrLink = true; )); $(window).bind("beforeunload", function() ( return inFormOrLink ? "Do you really want to close?" : null; ))

live method doesn't work with submit event, so if you add new uniform, you'll also need to bind a handler to it.

Note that if another event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You can fix this by recording the time in the submit and click events and checking if beforeunload is more than a couple of seconds away.

Just check...

Function wopen_close())( var w = window.open($url, "_blank", "width=600, height=400, scrollbars=no, status=no, resizable=no, screenx=0, screeny=0"); w.onunload = function() ( if (window.closed) ( alert("window closed"); )else( alert("just refreshed"); ) ) )

As of jQuery 1.7, the .live() method has been deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()

$(window).bind("beforeunload", function() ( return true || confirm("Do you really want to close?"); ));

Good afternoon. I recently posted an article on how to do it, but many asked to add an article with a mirror effect so that a window would appear when a visitor leaves the site, that is, when they try to close the page.

Today we’ll talk about this topic, and I’ll show you a simple implementation.

Of course, the debate about whether or not you should add a close popup to your site will never cease. Some say that there is a special place in Hell reserved for those who add it, that this is wildly infuriating, that if I decided to leave, then I will leave and no pop-up windows will stop me, but will only annoy me. Others say that these pop-ups increase conversions and work great. I think it’s worth a try, and then, based on statistics, draw specific conclusions regarding your niche and product.

How to make a popup when closing a page

In fact, I didn’t make any further ado and just slightly changed the previous article and added a few lines of javascript code. Previously, a modal window appeared when you first visited a site. Now it will only be shown on the first visit to the site (when the cursor leaves the main area of ​​the site and moves to the tab area). If the user visits the site again, this window will not be shown. This is implemented in exactly the same way as in the previous article, using cookies. Cookies are stored for 7 days, you can specify any quantity at your discretion.

And yet, we do not attach an event to a click on the cross in the tab, but simply check the position of the cursor. We do not block the window, buttons, etc., we do not require anything, but simply show the window.

Like last time, we will use the jQuery plugin arcticModal, which means we will connect jQuery itself:

And we connect the plugin theme, I use the standard one, but you can write your own:

Now, for our cookies to work, we will add the cookies plugin from Yandex:

And connect the config.js script with the following content:

$(document).ready(function () ( if (!$.cookie("smartCookies")) ( $(document).mouseleave(function (e) ( function getWindow() ( $(".offer").arcticmodal (( closeOnOverlayClick: true, closeOnEsc: true )); setTimeout(getWindow, 1); $.cookie("smartCookies", true, ( expires: 7, path: "/" )); );

If you read the last article, you noticed that nothing has changed, except that the script in the config.js file has changed slightly. That is, another condition has simply appeared that is triggered when the cursor leaves the site area, that is, is in the area of ​​​​the tabs.

By the way, last time I forgot to explain what these parameters mean:

CloseOnOverlayClick: true, closeOnEsc: true

  • closeOnOverlayClick - allows you to close a window when you click on any area outside the window.
  • closeOnEsc - closes the window when pressing Escape

Now about the page layout itself. Absolutely nothing has changed.

Your proposal, form, etc. will be here. You can insert a form or offer to follow you on social networks

I'll explain a little. modalInner — wrapper modal window, with display:none in the styles. offer is the class of the modal window itself. If you change it, don’t forget to change the class in the script.

Here is a simple implementation of a pop-up window when closing a page. Do you think it’s worth using a similar effect on a website?

“onbeforeunload event does not display site-supplied text, only standard message”, judging by the comments, finally and irrevocably. In this regard, I wanted to write a little about the history of the issue.

Many people know that thanks to onbeforeunload, you can ask the user not to leave a web page if he has unsaved data (for example, written in a form, but not sent a message to the forum). To do this, just add something like this JavaScript:
window.onbeforeunload = function (evt) ( var message = "Document "foo" is not saved. You will lose the changes if you leave the page."; if (typeof evt == "undefined") ( evt = window.event ; ) if (evt) ( evt.returnValue = message; ) return message )
After this, ideally, if the user wishes to leave the page (by any means - close the tab, close the entire browser, reload the page, enter new address V address bar, go to a bookmark, etc.), he will see a confirmation request and leaving the page can be canceled. Previously, unscrupulous website authors tried to use this window to outwit the user and keep him on the page, for example, using the text “Click OK to continue working with the site and Cancel to close” (in fact, the buttons worked the other way around). Or even something scarier like “Click OK to confirm the $1,000 charge to your credit card.”

Then browsers got wiser and began adding helper text to make it more difficult to deceive the user. For example, here's how IE8 does it:

Almost the same text was in Firefox 3:


If you read it all, it becomes clear what the site reported and what the browser reported. However, you can still cheat.


Here we see a clear description of the actions directly on the buttons. It is already quite difficult to convince the user to click “Leave” to stay and “Stay” to leave. In my opinion, the solution is ideal and this topic can be closed. In general, as you know, the faceless OK in almost any dialog should be replaced with the name of the action (for example, “Delete files”, “Search”, “Add line”, “Open file”, etc.), this reduces the number of user errors, even if you have complete control over the text of the dialogue.

What was the drama with bug 641509? The fact is that this confirmation in Firefox 4 and higher looks like this:


As seen, custom text disappeared altogether. As of version 4, the website cannot provide any additional message to the user or explain why specifically it does not want the user to leave. Let's say, if you are implementing an interface for working with many documents in one window, and one of them is not saved, you could tell which one specifically, but in Firefox you will not understand this. Perhaps you don’t want to save it and if you saw the message, you would calmly leave the page, but otherwise you don’t know what’s going on. In the sheet