Run a script when you go to a new page - javascript

How can I run a javascript function when the user exits my page? It's pretty much all in the title.

If you're talking about a redirect, like a link clicked from your page (which opens in a new tab), you can use event.preventDefault(), run your script and then do the redirect manually.
If you're talking about detecting when a user leaves the view on the browser, like many news/blog sites do when then they pop up an annoying "Don't miss out!" or "Sign up now!" modal, you can run the mouseleave or the mouseout event handler for either window or document.body and your script will run when the user moves the mouse outside the boundaries of the view, whether to another window/program or to the tab bar or URL bar within the browser window

Related

Best way to detect browser window changes like go back, url change, reload, close event

So I am working on a testing application and I need to call a finsihTheTest() function (i.e. this function finishes the test by saving answers, time and other information) whenever following conditions occur:
User tries to reload page.
User tries to go back from the page.
User tries to close the tab.
User tries to close the browser window.
User goes to another url.
If anything happens that closes the page like laptop/PC shutdown, internet lost or anything else.
What I exactly want to do is, if once a user starts the test and by any mean he attempts to leave I want to save his state. Which is being done by the function finishTheTest().
I got a clue but it didn't work:
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
To get the full results for your cases there's many things you should now on how browsers react on many scenarios.
To understand more please read this section :
Especially on mobile, the unload event is not reliably fired. For example, the unload event is not fired at all in the following scenario:
A mobile user visits your page.
The user then switches to a different app.
Later, the user closes the browser from the app manager.
Also, the unload event is not compatible with the back/forward cache (bfcache), because many pages using this event assume that the page will not continue to exist after the event is fired. To combat this, some browsers (such as Firefox) will not place pages in the bfcache if they have unload listeners, and this is bad for performance. Others, such as Chrome, will not fire the unload when a user navigates away.
If you're specifically trying to detect page unload events, it's best to listen for the pagehide event.
window.addEventListener('pagehide', function(event) {
document.cookie = "saveData=test"
},false)
This way you can save your user current data and reload it on next page window load event

Is there anyway to detect when a user goes to their homescreen and back into their browser?

I need to be able to detect when a user re-opens their browser after they go to their homescreen by clicking the home button on a mobile phone.
Is there an event I can subscribe to or something?
EDIT: To make this extremely clear, I am looking for a solution based in the web, not a mobile app. I need a js event or something to detect when my website is reopened.
The unload event can be monitored to check if the page has been closed dues to navigation away from the page or specific user action has been take to close the page.
The beforeunload evemt is similar to unload but it may be possible to ask if the user wants to stay on the page. If you want to debug when this event occurs I would suggest saving a message in local storage and logging (or otherwise alerting) it in debug code when the page is loaded again.
The blur event can be used to see if the page has lost focus by checking the relatedTarget property of the event object - if focus has been transferred off page it will be null.
None of these can implicitly check if the user actually went to the home screen and came back, and I would consider it a security breach if you could tell exactly. The blur event can at least tell if the page has lost focus, but will fire in a desktop environment if the user clicks on, say, the address bar.

What's window.onunload?

Im a beginner and i see that line of code a lot on javascript files , for example :
window.onunload=function(){};
when should i use this and what is it role exactly ?
thank you .
This function gets called when the user closes the browser or navigates away from the page.
https://developer.mozilla.org/en/DOM/window.onunload
You also might want to check out onbeforeunload, which allows you to prompt the user with a confirmation message before leaving the page. This can be useful for reminding the user to save their changes, or making sure the user doesn't actually want to claim their free iPad 2.
onunload is an event that is triggered when the user navigates away from your page, or when the page is "unloaded".
It's triggered when a user follows a link, or closes the tab. It's used for clean up. Like saving a user's data when they leave the page. Usually it's paired with onbeforeunload (which is called before onunload is using the same criteria) to warn a user that they have unsaved data.
if a page has an onunload handler, browsers that restore the page state (remembering changed form field values, script environment) when you navigate away and back to the page do not-
that is, they load the page as if it was the first time it was opened, with no user applied changes.

Browser window close and tab close

I want to create a JS function that detect only browser close and tab close functionality.
I used this code from http://ykyuen.wordpress.com/2011/02/22/jquery-javascript-capture-the-browser-or-tab-closed-event/
I works for me but when i place a cursor on address and hit enter it goes to kill page method. I need only to show alert when tab or browser is closed.
I am afraid this is not possible.
You cannot really make a distinction. When the user navigates away from your page in any way, you get the same events (beforeunload, unload). You can do some tricks (like in the link posted) whether the user clicked any of the links on your page or submitted one of your forms, but you cannot really differentiate between the refresh button, back button, the user entering a new address, the user clicking a bookmark, close tab, close browser, etc.

How to capture open link in new tab or window using jQuery?

Is it possible to capture the right click open in new window/tab or mouse wheel open in new window/tab event using jQuery?
UPDATE 1
Here is why I need it. I have codeigniter application which uses pagination class. I use this class to display a grid. The pagination links have been bind with a method that uses AJAX to load the next page in a container div. Now some one can right click and open the next page in new tab/window which I don't want. IMHO, the only way to handle this is to some how trap the (right click or mouse wheel button click) open in new window/tab event.
UPDATE 2
I just realised all my AJAX requests are being served by one CI controller which actually acts as a proxy to other classes/libs. In this controller I can look at the request and if it isn't an AJAX request I can redirect the user to another page.
A workaround solution is to replace all applicable <a> elements with buttons, where (obviously) the buttons would call JavaScript that does the appropriate navigation.
If you're really keen you can apply CSS to make the buttons look like <a> elements, though I don't recommend it because it confuses users who might try to treat them as standard links and right- or middle-click them.
(You could even get it to work for users that don't have JavaScript enabled by, e.g., making each button a submit button in its own little form.)
At the very least you can catch a right-click, using .mousedown() (or, presumably, mouseup()). See this StackOverflow answer about right clicks for more. And by catching it, you should be able to do a standard event.preventDefault() and then do as you like from there. That may be overkill, however, as it could prevent the user from doing other things you want to allow them to do.
I almost fixed a similar issue now for a page which I am working on. My fix was to do some changes in the page if that has been opened in a new window....
Assume that you open a page "B" from page "A" in a new window.
If you want to check the page "B" is opened in a new window from page "A", then follow the below steps..
If (document.referrer == "A" && window.history.length > 1) {
alert("I am page 'B' and opened from page 'A' in a new window");
}
If you don't want people to access link the usual way or fallback when the JS is disabled, then it shouldn't be a link. Just use any element you like (span, div, button, whatever you like) and style it like a link. Then bind the action using JS. Or you can use a link with href="#" or href="javascript: void(0)". That way if users right click it and choose to open in a new window, then they will end up in the same page they were before.

Categories