Anil
Anil

Reputation: 51

window.onbeforeunload error

We currently have a JS that popups a window whenever the visitor wants to leave the site. It works fine, except when hitting the back button on the browser, it popups up the alert even if we are on the site. we want to fix this.

Please note: -we do not want to disable the back button -we do not want to erase the historial

the JS function is onbeforeunload. it is currently loading everytime the user wants to leave the site. When the user navigates the site, on every link that we DO NOT want to trigger the popup, we add this: onClick="changes=true;" to the href.

As I mentioned, problem is when user hits back button, FWD and sometimes refresh.

here is the website url link text

Upvotes: 0

Views: 898

Answers (2)

bobince
bobince

Reputation: 536567

+1 what stefanw said. Don't do this. Everyone will point and laugh at your site.

You can't tell the difference in an unload between someone closing your window and someone using the back/forwards/refresh buttons, or bookmarks, or just typing a new address.

The only way to do it would be to have another (eg. pop-up) window present that keeps monitoring the other window to check the URL. If window.closed, or you can't access the URL due to same-origin restrictions, the user has left your site and then you can pop something up nagging at them.

Especially don't do this. Everyone hates pop-ups and would just close them. Everyone hates nags. Pop-ups and nags together are a recipe for no more site visitors.

There again, I've just looked at what your site is. Go ahead with the pop-ups. Or why not just delete your site and find something actually useful to do, instead of affiliating yourself with the worst spammers on the net?

Upvotes: 1

stefanw
stefanw

Reputation: 10570

Remove the onbeforeunload-Event entirely. Don't bully your visitors! If they want to leave your website, you shouldn't try to keep them there, it's annoying.

The only valid reason to use the onbeforeunload-event is when the user has changed something on the site and tries to navigate away from the site without saving the change.

Upvotes: 9

Related Questions