2011-08-23 55 views
10

我有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"; 
    } 
} 

的处理程序,但我不知道怎么知道他们是否在页面上点击链接是网站内。

我只希望他们提醒他们,如果他们将离开该网站。

+21

请不要这样做 - 他们知道他们要离开网站 - 他们点击链接。这种事情是什么给JavaScript一个坏名字。 –

+1

可能重复的[我如何在JavaScript onbeforeunload事件中获取目标网址?](http://stackoverflow.com/questions/1686687/how-can-i-get-the-destination-url-in-javascript-onbeforeunload -event) –

+0

2 UP投票? .... – Nivas

回答

17

不可能100%可靠地做到这一点,但如果您检测到用户点击了您网页上的链接,则可以将其用作大多数正确的信号。事情是这样的:

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 
    } 
} 
+1

非常好,不显眼的解决方案 –

1

我有一个想法,但我不知道它是否工作。我的建议是,通过函数调用为每个链接添加一个onClick事件。该函数只读取href属性并将其存储到全局范围的变量中。

var clickedHrefAttrValue = ""; 
function getClickUrl(currentLink) 
{ 
    clickedHrefAttrValue = $(currentLink).attr("href"); 
    return true; 
} 

的一个标记的HTML必须看起来像以下:

<a href="<url>" onClick="getClickUrl(this)">Linktext</a> 

,并在给定的功能:

function getClickUrl() 
{ 
    if (clickedHrefAttrValue.indexOf("<your condition>" > -1) 
    { 
    //what ever you want do to 
    } 
} 

这只是一个想法,但我认为这是值得去尝试一下。

0

如果您有问题,因为你的网站可能有绝对和相对本地链接,我有(使用jQuery)另一种解决办法:

Demo

/* EXTERNAL LINK WARNING 
=========================================*/ 
$('a').on('click', function(e){ 
    e.preventDefault(); 
    var url = $(this).attr('href'), 
     host = location.host;  
    if (url.indexOf(host) > -1 || url.indexOf('http','https') == -1){ 
     /* If we find the host name within the URL, 
       OR if we do not find http or https, 
       meaning it is a relative internal link 
      */ 
     window.location.href = url; 
    } else { 
     var warn = confirm('You\'re leaving the domain.\n\nAre you sure?'); 
     if(warn == true) { 
      window.location.href = url,'_blank'; 
     } else { 
      e.preventDefault; 
     } 
    } 
}); 
-1

有这是我最近在网站上实施的一个很好的解决方案。试想一下,网站上浏览用户的所有内容都将成为链接(锚标签),按钮,可点击图片或其他内容。它绝对不会是身体的元素。

现在,当用户离开网站时,他/她可以输入url并按下回车键,单击书签或按下后退/前进按钮。

当用户不这样做,这样做:

$(window).on('beforeunload', function(e)){ 
    if(e.target.activeElement.nodeName.toLowerCase() == 'body'){ 
     yourFunction(); 
}); 

什么情况是,身体变得目标中的活性元素在这些情况下(当用户离开网站),这是不是这样的当用户点击内部网站导航元素时。

这是一个干净,简单的解决方案。如果您遇到任何问题,请告诉我。

+1

但这个动作也会在刷新时发生。 – Gags

相关问题