Reputation: 6723
I want to be able to tell when a window that I open is closed by the user. This is the code of my attempt at monitoring this:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
window.document.onready = function () {
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.onunload = function () {
window.alert('hola!');
};
};
};
</script>
</head>
<body>
<button id='openWindow'>Open Window</button>
</body>
</html>
I would expect this to alert "hola!" in the original window after the window that was opened with window.open
was closed. Instead, it alerts "hola!" in the original window immediately after opening the new window with window.open
. Why does it work like this? Is there a way of doing what I want to do?
Upvotes: 15
Views: 29105
Reputation: 131
Very late response to this one, but I've just had the same issue with this code in an aspx page:
function handleButton() {
var myPopup = window.open('/Home/MyPopup', 'Popup');
myPopup.addEventListener("unload", function (x) {
console.log(x.results);
});
}
<button onclick="handleButton()">My Button</button>
My mistake was to omit giving the button a type="button"
, so the page defaults to type="submit"
and posts back when the button is clicked (I assume removing the reference to the event listener when the page reloads). Giving the button a type of button fixed the issue:
<button type="button" onclick="handleButton()">My Button</button>
Upvotes: 1
Reputation: 3222
Digital Plane answer seems to work, but it feels a bit brittle (e.g. if the browser changed behavior and stopped loading/unloading "about:blank" the event would stop firing.)
My solution was to check windowref.location.href
of the popup and skip the handler when it is "about:blank":
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.addEventListener('unload', () => {
if (windowref.location.href === "about:blank")
return;
window.alert('hola!');
});
};
Upvotes: 1
Reputation: 38264
The window first loads with a blank page and then unloads the page, causing the unload
event.
Your page then loads. Try attaching the event when the onload
event fires to avoid this.
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.onload = function() {
windowref.onunload = function () {
window.alert('hola!');
};
}
};
Upvotes: 34
Reputation: 207501
Try adding after the window loads
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.window.onload = function(){ //wait til load to add onunload event
windowref.window.onunload = function () {
window.alert('hola!');
};
}
};
Upvotes: 1