How to show confirm when browser window got closed or navigated to another website in JS
As the title says ....
Sorry that some ppl got question wrong...
I want to show confirma开发者_运维百科tion on these cases only:
1.Browser window is closed.
2.There is a redirect to different domain
thanks
By using the onbeforeunload event:
window.onbeforeunload = function() {
return 'Are you sure you want to navigate away from this page' ;
};
The first question has already been very well covered.
Alerts when navigating away from a web page
The second part is more troublesome. You won't get anything in the onbeforeunload event that tells you which link was clicked on to trigger it.
If you wanted to detect which link caused the close you'd have to attach some script to each link's onclick event. You'd also have to remove the href from the link and store it somewhere, you could do it like this using jQuery:
<script>
$(window).load(
function () {
$("a").each(function () {
$(this).data("url", $(this).attr("href")).attr("href", "#").click(
function () {
var destination = $(this).data("url");
// do something to check the domain, I'm just checking the whole url
if (destination == "http://norman.cx/photos/") {
alert("Not navigating to: " + destination);
} else {
alert("Navigating to: " + destination);
window.location.href = destination;
}
return false;
}
);
});
}
)
</script>
<a href="http://norman.cx/photos/">test</a>
<a href="http://microsoft.com/">msft</a>
This gets the href for each link, stores it against the link using data() and sets the link's href to "#". It then attaches a click event to each link that retrieves the url from data() and does something with it.
You could do it the other way, conditionally change the href and add the click event only on links that where on another domain.
Whether that would be a good idea or not is another question. It is at the very least an unusual thing to find yourself doing.
<body onunload="doYourThing();" >
精彩评论