Check if user hits back button in browser
I'm trying to use the javascript onbeforeunload event to ask the user if they want to exit the page, but I don't want the event to fire (EDIT: "the event" being the dialog box that pops up asking the user to click开发者_开发知识库 ok to leave the site or click cancel to stay on the current page) if the user hits the back button since they will be most likely be staying on my site.
So is there a way to tell if a user has hit the back button using javascript or PHP?
I've gotten a solution using a hidden iframe that only works in IE, but I need something that can work for Firefox, Chrome, and Safari if possible.
EDIT: My IE solution works because when the user hits the back button the iframe is sent back but the parent page remains at the same spot. From this I can tell that the user has indeed hit the back button, so I then use history.back(). This little hack doesn't work in any other browser (to my knowledge), so I'm looking for a cross-browser solution.
tl;dr I'm using window.onbeforeunload to pop up a dialog asking users if they want to leave my site or not. I don't want this to pop up when the user hits the back button. How can I tell that the user has hit the back button in their browser?
Thanks, Rick
Short answer:
No.
Long answer:
Noooooooooooooooooooooooooooo.
please don't try to keep users on your website unless you have a very good reason to. Saving form fields would be an example of a good use. Checking if they're moving on to another website would be a bad use.
People don't travel from page-to-page as much as they did in the early days of the web. Instead they use google and social networks to find interesting pages, and consume separate distinct pieces of information.
You can't know in advance on which page your user will go when he leaves your page. You can't even get the URLs in its current history.
I see no solution to your problem and I doubt there's one, sorry.
If you don't want anything to happen when the user clicks the back button, then you don't necessarily need to determine if the back button has been hit.
Your goal is to determine who will "most likely be staying on [your] site," and create an extra step for everyone who wants to leave. You're trying to interrupt and override the user's expectations of how his browser will behave.
If you really want to do this, have event listeners for all unload events that aren't triggered by the back button: every link on your page, closing the window, etc. It won't be easy, and you won't be able to catch all events. But you're going to be pissing people off unless you have a good reason for doing this, so if it's really important then put the extra effort in.
tl;dr: Add event listeners to everything that isn't the back button and bring up the dialog in the callback function. It will piss people off, though.
精彩评论