I have a handler for onbeforeunload
window.onbeforeunload = unloadMess;
function unloadMess(){
var conf = confirm("Wait! Before you go, please share your stories or experiences on the message forum.");
if(conf){
window.location.href = "http://www.domain.com/message-forum";
}
}
but I'm not sure how to know if the url they clicked on the page is within the site.
I just want them to alert them if they will leave the site.
The most reliable way to detect when a user leaves a web page is to use visiblitychange event. This event will fire to even the slightest changes like changing tabs, minimizing the browser, switching from browser to another app on mobile, etc.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
The Onunload event handler in Javascript is an event handler that is triggered when a user leaves the current web page.
It's not possible to do this 100% reliably, but if you detect when the user has clicked on a link on your page, you could use that as a mostly-correct signal. Something like this:
window.localLinkClicked = false;
$("a").live("click", function() {
var url = $(this).attr("href");
// check if the link is relative or to your domain
if (! /^https?:\/\/./.test(url) || /https?:\/\/yourdomain\.com/.test(url)) {
window.localLinkClicked = true;
}
});
window.onbeforeunload = function() {
if (window.localLinkClicked) {
// do stuff
} else {
// don't
}
}
I've got one idea, but I don't know if it's work. My suggestion is, add each link an onClick event with a function call. That function reads just the href attribute and store into a variable with global scope.
var clickedHrefAttrValue = "";
function getClickUrl(currentLink)
{
clickedHrefAttrValue = $(currentLink).attr("href");
return true;
}
The html for the a tags must be looks like following:
<a href="<url>" onClick="getClickUrl(this)">Linktext</a>
and in your given function:
function getClickUrl()
{
if (clickedHrefAttrValue.indexOf("<your condition>" > -1)
{
//what ever you want do to
}
}
It is just an idea, but I think it is worth to try it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With