Check if user button clicked in browser

I try to use the onbeforeunload javascript event to ask the user if they want to leave the page, but I do not want the event to fire (EDIT: β€œevent” is the dialog box that appears the user clicks β€œOK” to leave the site, or click "Cancel" to stay on the current page) if the user clicks the "Back" button, as they are likely to remain on my site.

So, is there a way to find out if the user clicked the button back using javascript or PHP?

I have a solution using a hidden iframe that only works in IE, but I need something that can be used for Firefox, Chrome and Safari, if possible.

EDIT: my IE solution works because when the user accesses the back button, the iframe is sent back, but the parent page remains in the same place. From this, I can say that the user really clicked the back button, so I use history.back (). This little hack doesn't work in any other browser (as far as I know), so I'm looking for a cross-browser solution.

tl; dr I use window.onbeforeunload to open a dialog box asking users if they want to leave my site or not. I do not want this to pop up when the user clicks the back button. How can I say that the user clicked the back button in his browser?

Thanks Rick

+4
source share
3 answers

Short answer:

No.

Long answer:

Noooooooooooooooooooooooooooooo.

please do not try to keep users on your website unless you have a good reason . Saving form fields would be an example of good use. Checking if they are switching to another site will be bad.

People do not move from page to page as much as in the early days of the Internet. Instead, they use google and social networks to find interesting pages and consume individual individual pieces of information.

+7
source

You cannot know in advance which page your user will go when he leaves your page. You cannot even get the URLs in your current history.

I do not see a solution to your problem, and I doubt that there is one, sorry.

+3
source

If you do not want something to happen when the user clicks the back button, you do not need to determine if the back button has been pressed.

Your goal is to determine who β€œis likely to stay on [your] site” and create an extra step for everyone who wants to leave. You are trying to interrupt and redefine user expectations about how his browser will behave.

If you really want to do this, event listeners for all unload events that are not triggered by the "Back" button: every link on your page, closing a window, etc. It will not be easy, and you won. It is impossible to catch all the events. But you are going to expose people if you have no good reason for this, so if it is really important, add extra effort.

tl; dr: Add event listeners to anything that is not the back button, and invoke a dialog in the callback function. However, it will break people.

0
source

Source: https://habr.com/ru/post/1332832/


All Articles