What's window.onunload? - javascript

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.

Related

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.

Prevent the URL from changing when popstate occurs

Hi I'm trying to implement a "Are you sure you want to leave this page?" popup when navigating away from a page with a modified form that hasn't been submitted. The website is a single page app built using a custom framework.
Since all anchor links are handled by the framework it can tell that clicking a side nav link will cause a page change and show a Bootstrap confirm dialog. If the user clicks "Ok" the click goes through and an AJAX call is made to pull the new page content. If they click "Cancel" the modal is dismissed and they stay on the current page.
The part I haven't been able to solve is when a user clicks the "Back" button in their web browser. This triggers the "popstate" event. All navigation/history is managed using the history API since it's a single page app.
The issue is that when someone clicks "Back", the URL changes since "popstate" occurred, then I show my "Are you sure you want to leave?" modal. When the event occurs the URL in your address bar now shows the page you would go to from your history, not the page you're currently viewing. If you click "Cancel" in the Bootstrap confirm you are now left with the wrong URL displayed in your address bar.
event.preventDefault, event.stopPropagation, or return false inside popstate don't stop the URL from changing. AFAIK you can't intercept the "Back" button before "popstate". Trying to window.history.replaceState inside "popstate" doesn't seem to work either.
Does anyone have a solution on how to make this work?
Can you stop the URL from changing in the "popstate" event?
Can you rewrite the history somehow in "popstate" to change the URL back to what it was on the current page and retain the previous entry if you do decide you want it to go through after a modal has been accepted?
Some other solution I haven't thought of?
My original thought was to block the URL change in "popstate" then let the framework trigger the link click to load the new content and change the URL if they click "Yes" but I haven't found a way to do that.
Thanks!
I solved this by doing the following;
Each time a history state is created I generate a timestamp as a guid
The current timestamp is stored in a variable on the top level module
When popstate occurs the incoming history state's guid is compared against the top level modules guid
If the new guid is greater we're going forward, if it's less we're going backward
When the user clicks the back/forward button the hash does change to the incomming URL. If the user clicks cancel it runs history.go( direction ) where direction is 1 or -1 depending on the timestamps. This sets the URL back to what it should be and doesn't do anything weird to the history stack. The top level history variable has a flag to know that we're faking a page change so the link load logic in popstate is not executed.
The only quirk is if the user does click yes to navigate away when that request is sent and returned and a history object is created you do not update the top level module's guid. If you do the guid comparison will always think you're going backward because the new event you just added will always be the highest number. This may not be an issue if you don't make new requests for history URL's but our framework does so it doesn't display stale data like the browser typically does.
It's not ideal since you do see the URL change (no content changes) but so far it seems to work well enough. Another solution I found was to store your own site's history in local/session storage and compare URLs instead of using guid timestamps to find the popstate direction. This won't work in Safari's private browsing mode since both storage layers are disabled so I opted for guid's.

onbeforeunload any way to know if it is reload or leave?

We have some forms that users fill out. If during the process the navigate away I need to perform an action.
I've found many examples of combining onbeforeunload and unload in the browser to prompt the user the user and remind them that if they close or navigate away the information they have entered won't be saved. That part is working well.
The only problem I still have is if the user reloads -- right-click reload, F5, or browser refresh button -- then the unload is also called. This is a problem for us.
I found information about the performance.navigation property. But the values of that aren't available until after the page reloads, that is, it tells me that the page I'm on has been reloaded, but not that the page is about to be reloaded.
Is there any way to detect an impending refresh as opposed to a navigate away?
No.
I recommend you "perform an action" as your user is filling out the form. Then if the user chooses to leave, no harm done.
It's perfectly feasible to post this information to a server as it is being populated. If the "perform an action" requires interaction with the user, you should just do that interaction on beforeunload.
EDIT: At the point of beforeunload, the only interaction that can be provided is an alert() asking the user to OK / Cancel navigating away from the page.

Executing a function on initial page load (and user refreshes) but not back button

I'd like to execute a javascript (or jQuery) initialization function -- let's call it myPageInit() after a page is fully loaded.
Here's the catch: myPageInit() should run only when the page is initially loaded or if the user forces a page refresh (i.e. presses the browser's reload button, hits F5, etc.).
It should not run if the user follows a link from the page and then hits the back button.
For the avoidance of doubt:
User navigates to www.mypage.com => myPageInit() runs after page is loaded.
User now hits browser refresh button => myPageInit() runs after page is reloaded.
User now clicks on a link on the page (e.g. <a href="www.cnn.com">... ).
User clicks back button to get back to www.mypage.com => myPageInit() does not run after page is shown.
What I've tried so far
$(window).load() -- I think this used to work, but on modern browsers this appears to fire when the user presses the back button (see the comments on this issue)
$(window).ready() -- This also appears to fire on both initial load and back button.
Searching SO for other relevant answers. I still haven't found what I'm looking for.
Thanks in advance!
Maybe not exactly what you needed, but how about a session cookie or HTML storage flag? See code and answers at:
e.g. create session based cookie, jquery

JavaScript problem toolbar=no

I have a simple logon page. When the user is validated, the window navigates to a new page. The javascript is window.open('http://www.google.com',"mytest",'toolbar=no'); My expectation is that when it navigates away from our logon page and opens the google site that the back button would be disabled. But it's not. Does anyone have any idea why?
It depends on your browser. Ultimately, all you can do with javascript's window.open() is tell the browser what you'd like it to do, but it's not obligated to do it. Browsers can and do ignore some directives based on user preferences.
I believe the option your looking for is 'location=no', as that hides the address bar and therefore the back button too. The toolbar is things like favorites/etc.
This is bad practice - what happens if the user has javascript disabled? If the browser prevents the js from removing the toolbar of the main window?
Instead, amend the logon page to detect whether the user is logged in before showing the login form. If logged in, show a message saying so instead of the form - that way, a user clicking back won't be a problem.
I find it very annoying when a website messes around with my browser window, and generally don't come back.
This is what worked for me. Instead of disabling the back key. I listen for on unload event. I then write the following in javascript:
window.onbeforeunload = function () { return "You should not press the back button while in this application. If you continue, your work will not be saved and you will need to log back in."}
Java Script pops a dialogue box with OK and Cancel options. If the user clicks cancel. The application stays right where they are. The script is embedded within the tags. For me this is the ideal solution. I found this at
http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

Categories