2

I've seen many examples how to ask user if he really wants to leave a currently opened page, but I've never seen code that would warn user about leaving a page only if he's leaving to certain pages, while silently allowing it for other pages.

Basically, I would need a property that gets set to a future page's href when new url is clicked (or some other event triggers).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hummingBird
  • 2,495
  • 3
  • 23
  • 43

2 Answers2

3

From a similar question: How can i get the destination url in javascript onbeforeunload event?

What is possible is to capture the onbeforeunload event. What it is not possible to do is get the url of the page the user is going to. One unorthodox hack is to get the URL of the link last focused on, but that is a infringing on a user's privacy.

Community
  • 1
  • 1
mattsven
  • 22,305
  • 11
  • 68
  • 104
  • 1
    That only works if the user actually followed a link on the page. The OP can simply put an click listener on those links to do the job, the beforeunload event isn't needed. Such warnings are really annoying though, the user should be aware of whatever issue might cause beforehand (e.g. use a style or onscreen hint). – RobG Mar 29 '11 at 06:43
  • thx for the link, but this doesn't answer it. answer seems to be 'NO' :) – hummingBird Mar 29 '11 at 10:14
  • i will select it as answer, anyway – hummingBird Mar 29 '11 at 10:14
2

You are looking for the onbeforeunload event.

Example

var dontLeave = function(e){
    return "DONT LEAVE MY PRECIOUS!!";   
}

window.onbeforeunload=dontLeave;
Loktar
  • 34,764
  • 7
  • 90
  • 104