Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 645
Rick Avatar asked Dec 28 '22 03:12

Rick


1 Answers

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.

like image 79
zzzzBov Avatar answered Jan 09 '23 06:01

zzzzBov