How to detect the window(new tab) close event? - javascript

I have one parent page and child page. the child page opened in new tab
I want to show one alert message (The child page is closing), when i close the child tab.
How to show the closing messgae, when close the tab? (Not refreshing time)
I used onunload, and onbeforeunload.
Two methods are also called, when the page refresh and tab closing.
window.onunload = function doUnload(e)
{
alert('Child window is closing...');
}
and
window.onbeforeunload = function doUnload(e)
{
alert('Child window is closing...');
}
I must show the alert message, only close the tab in browser.
Help me.
Thanks in advance.
Update
I use the following script. Its worked In IE. But not worked in FireFox
<script language="javascript" type="text/javascript">
window.onbeforeunload = function()
{
if ((window.event.clientX < 0) || (window.event.clientY < 0) || (window.event.clientX < -80))
{
alert("Child window is closing...");
}
};
</script>
How to acheive this in FireFox and other Browser.

There is afaik never been a cross browser script for this. The solution is to NOT rely on undocumented and changeable features of a specific browser to detect something that is important.
Since you have a CHILD page, you can set up a test in the parent (opener) that at intervals test the childWindowHandle.closed property and acts on that.

Does the script from http://chrismckee.co.uk/good-sir-before-you-unload-crossbrowser-javascript-headaches/ work?
Assuming your just trying to fire beforeunload event crossbrowser, this pretty much does it ( excluding 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;

There is an example in Mozilla Devloper site which basically says check for browser type
and use the below check accordingly.Hope this helps.

You might not be able to do that other than some cookie based methods which is development work arounds like non persistent cookies. Second identifying a page refresh, form based redirect, or back redirect or browser close unload event identification is not direct and is tedious. Recommend not to depend on it.
you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it. Yes, you cannot at this time differentiate back and refresh and close. So no foolproof way of saying whether the child has definitely 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
});
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

Related

window.onbeforeunload not working properly after postback/page load

I've got this simple function that prevents users to accidentally close browser pages (in my case on chrome) prompting a confirmation message.
window.onbeforeunload = function () {
return "Are you sure you want to leave this page?";
};
It works all fine but i found some limitations:
on page load the function doesn't work if you first don't interact with the page in some way
e.g. click somewhere in the DOM
This behavior is particularly annoying inside the classic asp net application (web page) that loads data from a DB into a gridview because every time data is loaded the postback appends and if you close the tab no confirmation message appears. (i know you can use UpdatePanels to avoid the postback, but it's not the solution i'm looking for)
I tried to generate a click on some element of the DOM on page load:
$('#someID').click();
but didn't work.
Any ideas?
According to https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload :
You can and should handle this event through window.addEventListener()
and the beforeunload event. More documentation is available there.
The linked articles go on to state:
WebKit-based browsers don't follow the spec for the dialog box. An
almost cross-browser working example would be close to the following:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
try using $('#someID').focus() instead of $('#someID').click().
$(document).ready(function () {
$('#someID').focus();
});

onbeforeunload onunload performance.navigation.type not working properly

I have reactjs application, I am trying to show the alert on the browser close.but some inconsistent behaviour is coming. Sometimes it is not firing the alert on the browser refresh but sometimes it is showing the alert.Below is my code:-
window.onbeforeunload = () => {
let msg =undefined;
if (window.performance && performance && performance.navigation.type == 1){
}
else{
msg ='Are you sure?';
}
return msg;
};
window.onunload = () => {
if (localStorage.getItem('state')) {
localStorage.removeItem('state');
}
}
Now sometimes it showing the alert on browser close button click, but sometimes it closing the browser without any warning, also some time on refresh alert is coming which is not expected in my scenario.I want to show the alert only on the close of the browser.Please assist me how can I handle this scenario.Many duplicate questions like this is also present in StackOverflow but all answers are old and they are not using the modern browser concept.
You can't detect if the user wants to reload or if they want to change the page within the window.onbeforeunload or window.onunload events.
The PerformanceNavigation API only tells you how the user went to the current page, not how they will navigate to the next page on window.onbeforeunload or window.onunload events.

AngularJS how to show browser dialog protects before changing tab

I have to display a message which warns the user before changing tab without saving changes. An url in the browser does not change in this process because user changes only a tab.
SetPristine, SetDirty will not help me because the url does not change. Is there any way to display this system-browser popup manually? If not maybe can you tell me how to create identical alert in the same space (it is placed in top-center part of the website).
I would like to get a result similar to the picture below.
Thanks in advance :)
What your asking for is not an Angular only thing. You can do it in pure javascript.
What you're asking about is the beforeUnload event.
Here is some sample code from mozilla:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
This example prevents a dialog box, but to show one you need to set the return value to your dialog text:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
return "You will loose any unsaved changes, by leaving the page"
});
Another mozilla page explains in more detail
What this means is you can put other code in the event handler that will pop up a modal say, or some other dialog to inform the user about data loss.
If what you want is actually about changing tab, then the cleanest way is to use the Page Visibility API which is reasonably well supported now.
What you want is now more like so:
document.addEventListener("visibilitychange", handleVisibilityChange, false);

how to redirect in other page when browser close event called

I want to redirect in another page when browser is closed. My code is following:
<script language="Javascript">
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit(){
if (needToConfirm){
my_window = window.open ("1.html","mywindow1","status=1,width=350,height=150");
return "You have attempted to leave this page. If you have made any changes "
+"to the fields without clicking the Save button, your changes will be "
+"lost. Are you sure you want to exit this page?";
}
}
But when I am clicking on close button of browser, I am seeing an system confirmation message and I am also not getting pop up page opening in mozilla. How will i resolve this problem?
Thanks
Code excerpt from this page.
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
short answer:
your code works perfectly if you wouldn't have blocked it.
long answer:
this is a working example - and it's almost the same like yours (take a look at the sourcecode).
but: this works only if you're generally disabling the popup-blocker in FF (or create a rule to allow popups from that URL).
i'm sure the reason your code isn't working is the activated popup-blocker, wich shows this nice, yellow "site tries to open a popup"-warning wich isn't shown to you because the site is closed (so, you can't klick on "allow popups from this site").

is it possible to open a popup with javascript and then detect when the user closes it?

The question is pretty much all in the title.
Is it possible (and how?) to open a popup with javascript and then detect when the user closes it?
I am using jquery within the project so a jquery solution would be good. Cheers!
If you have control over the contents of the pop-up, handle the window's unload event there and notify the original window via the opener property, checking first whether the opener has been closed. Note this won't always work in Opera.
window.onunload = function() {
var win = window.opener;
if (!win.closed) {
win.someFunctionToCallWhenPopUpCloses();
}
};
Since the unload event will fire whenever the user navigates away from the page in the pop-up and not just when the window is closed, you should check that the pop-up has actually closed in someFunctionToCallWhenPopUpCloses:
var popUp = window.open("popup.html", "thePopUp", "");
function someFunctionToCallWhenPopUpCloses() {
window.setTimeout(function() {
if (popUp.closed) {
alert("Pop-up definitely closed");
}
}, 1);
}
If you don't have control over the contents of the pop-up, or if one of your target browsers does not support the unload event, you're reduced to some kind of polling solution in the main window. Adjust interval to suit.
var win = window.open("popup.html", "thePopUp", "");
var pollTimer = window.setInterval(function() {
if (win.closed !== false) { // !== is required for compatibility with Opera
window.clearInterval(pollTimer);
someFunctionToCallWhenPopUpCloses();
}
}, 200);
There is a very simple solution to your problem.
First make a new object which will open up a pop like this :
var winObj = window.open('http://www.google.com','google','width=800,height=600,status=0,toolbar=0');
In order to know when this popup window is closed, you just have to keep checking this with a loop like the following :
var loop = setInterval(function() {
if(winObj.closed) {
clearInterval(loop);
alert('closed');
}
}, 1000);
Now you can replace alert with any javascript code you want.
Have Fun! :)
Try looking into the unload and beforeunload window events. Monitoring these should give you an opportunity to call back when the DOM unloads when the window is closed via something like this:
var newWin = window.open('/some/url');
newWin.onunload = function(){
// DOM unloaded, so the window is likely closed.
}
If you can use the jQuery UI Dialog, it actually has a close event.
To open a new window call:
var wnd = window.open("file.html", "youruniqueid", "width=400, height=300");
If you just want to know when that window is going to close, use onunload.
wnd.onunload = function(){
// do something
};
If you want a confirmation from the user before the can close it, use onbeforeunload.
wnd.onbeforeunload = function(){
return "are you sure?";
};
We do this in one of my projects at work.
The trick is to have a JS function in your parent page that you plan to call when the popup is closed, then hook the unload event in the popup.
The window.opener property refers to the page that spawned this popup.
For example, if I wrote a function named callingPageFunction on my original page, I would call it from the popup like this:
$(window).unload(function() {
window.opener.callingPageFunction()
});
Two notes:
This should be wrapped in a ready function.
I have an anonymous function because you may want other logic in there
I thinks best way is:
const popup = this.window.open(url.toString());
popup.addEventListener('unload', ()=> console.log('closed'))
Yes, handle the onbeforeUnload event for the popup window and then call a function on the parent window using:
window.opener.myFunction()
This worked for me.
onunload event will be triggered whenever DOM is unloaded for example if url is changed and previous page DOM is unloaded and DOM for new page is loaded.
var newWin = window.open('/some/url',"Example");
newWin.onunload = function(){
if(newWin.closed){
// DOM unloaded and Window Closed.Do what ever you want to do here
}
}

Categories

Resources