I have just been helped on a problem I have here.
var win = window.open(url, name);
win.onunload = StartLoad;
win.close();
To solve this problem completely, I wanted to know if onunload will be triggered once or every time a event occurs?
In other words, will my function startLoad run every time the child window "win" gets redirected, closed etc? Or will it do this event once and that's it?
Apologies, if this is a silly question.
Thanks all
No - this method can fire multiple times as you navigate off a page in IE6 and IE7.
This code snippet illustrates this (save as OnUnloadTest.htm):
<body>
<form id="form" action="OnUnloadTest.htm" method="post">
Click here
</form>
<script type="text/javascript">
window.onbeforeunload = beforeunload
function beforeunload() {
alert('OnUnload');
}
</script>
</body>
Basically, the event fires once for the actual anchor click, and once as the page actually posts back. I've only seen this issue when you have javascript in the href of the anchor, although if you use ASP.NET linkbuttons then be warned as this puts javascript in the href.
For most other sorts of navigation (e.g. user clicks a normal anchor, or closes the browser, or navigates away with a bookmark, etc) the event does only fire once.
It should only fire once, the first time the window unloads. Anything else would be a security hole.
If you want to make sure that your event handler only runs once you can have the handler unbind itself the first time it is invoked. This will guarantee that the callback does not run more than once:
var win = window.open(url, name);
win.onunload = function(event) {
win.onunload = function() {}; // assign a noop
return Startload.call(this, event);
};
win.close();
Some JavaScript libraries have a built-in helper for binding an event handler that you only want run once. For example, jQuery has a one() method for this purpose:
var win = window.open(url, name);
$(win).one('unload', Startload);
win.close();
Read WebKit Page Cache II – The unload Event for interesting discussion on how unload event plays with page caching feature of modern browsers.
Related
I am working on a simple chat script using Ajax and want to indicate when a user leaves the page. Have read several docs and found this works:
window.onbeforeunload = leaveChat;
function leaveChat(){
... my code
return 'Dont go...';
}
Unfortunately (and logically), if they cancel the exit, my code is still executed and they are flagged as leaving even though they are still on the page? It should only execute if the confirm leaving the page. Any suggestions?
I would use onunload, but it doesn't seem to work in any of my browsers (Chrome, IE).
First, you should add the event handler using:
window.addEventListener('beforeunload', function() {
// Confirmation code here
});
window.addEventListener('unload', function() {
// fire pixel tag to exit chat on server here
// UI interactions are not possible in this event
});
For further research:
unload event reference
beforeunload event reference
Window.onunload reference
I'm trying to detect the exact moment when the page leaves its current location and begins loading of a new one: immediately after clicking on a link or pressing "submit" or any other way.
I'm aware of "onload" event and several ways to make use of it, but that's not what I'm looking for: plenty of time can pass between 1) clicking on link and 2) firing "onload" event and I need to detect the moment after 1).
I think what you're looking for is: onbeforeunload or onunload
I like using the onhashchange event:
window.onhashchange = function() {
console.log("Hash changed");
}
Demo: http://jsfiddle.net/v8j9F/
Reference: https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange
onbeforeunload is probably the earliest, it's described briefly here
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?")
});
I have a window that is opened by
var myWindow = window.open(
'popupManager.htm',
'myWindow',
'status=0,toolbar=0,width=500,height=100');
and it will act as a debug window.
inside I want to hook up to windows events on the window.opener and I'm not getting this to work. Both URL's are in the same domain/same website.
I can hook up to DOM elements fine using, for example
$("input[soid=DlgButtonBar_cancelButton]", window.opener.document).bind("click", function() {
alert('Cancel button was pressed!');
window.close();
});
but I want to hook up to the move event (window.onMove) and close event.
tried
window.opener.addEventListener('move', function() { console.log('moving...'); });
with no luck.
what is the trick? using jQuery or simple javascript...
Listening on window events doesn't seem to work. I use this trick to listen to window events (unload in my case):
Create a document element (e.g. span) on the parent document (e.g. the one you want to get events from) :
var $unloader = $('<span style="display:none;" id="unloader"></span>');
$('body').prepend($unloader');
$(window).unload(function(){$('#unloader').click();});
In the opened document (e.g. popout), you can listen to the unload event now masked as a click event:
$("#unloader",window.opener.document).click(unloadEventHandler);
If you need to detect if the unload is a close or a navigation event, you can check the closed property for the parent after a delay:
window.setTimeout(function(){
if(window.opener.closed == true) {
// Close event
} else {
// Navigation event
// window.opener.location to get new location
}
},500);
The risk is in the delay, the closed property is changed after the unload methods and event hooks are executed so if the delay is too short you might get the flag before it is changed and if it's too long, you get unnecessary delays.
I think the move event can be handled similarly, hope this helps. Let me know if there are any possible improvements to this method. Thanks and good luck.
I'm trying to set an onLoad event to the current web page from a firefox extension. I'm using the gBrowser object but I'm not sure if this is the best way. I would like to set an onLoad event to the web page window to execute some actions of the plugin as soon as the page is loaded.
Thanks in advance.
After several attempts I found a solution for this. Lets say we have a function called pageLoaded, which is the one we want to call when the website has been totally loaded. Now, we have to add an event listener to the gBrowser object to catch the load event.
Here the code:
function pageLoaded(){
alert("the page has been loaded")
}
gBrowser.addEventListener("load", pageLoaded, true);
I recommend to use add an event listener to the extension document before to add it to the gBrowser. The result would be something like this:
window.addEventListener("load", function () {
gBrowser.addEventListener("load", pageLoaded, true);
}, false);
I hope this solution will be useful for someone.
Thanks for reading.