I want that user should be given a popup whenever he/she navigates away from my website(not just the webpage, the entire site).
I have implemented a method but it pop-up every time on navigating away from webpage.
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to navigate away from myWEbSite?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt ) {
evt.returnValue = message;
}
return message;
}
You cannot get the new target url, since this is a protected information (see How can i get the destination url in javascript onbeforeunload event? )
So, you are not able to see, if the visitor leaves the website.
Alternative: you could listen all clicks on hyperlinks which refer to another webpage and implement a functionality which catches external links.
You can defile your own JQuery selectors, like this:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$.expr[':'].internal = function(obj){
return obj.hostname == location.hostname;
};
And then you can do the following:
$(function() {
var unloadMessage = function() {
return "Are you sure you want to navigate away from myWEbSite?";
};
$('a:internal').click(function() {
window.onbeforeunload = null;
});
$('form').submit(function() {
window.onbeforeunload = null;
});
$('a:external').click(function() {
window.onbeforeunload = unloadMessage;
});
window.onbeforeunload = unloadMessage;
});
In your specific case you just need to set window.onbeforeunload == null
whenever a navigational link is clicked or an internal form is submitted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.