重写问题-
我试图使一个页面上,如果用户离开的页面(无论是其他链接/网站或关闭窗口/标签),我想显示onbeforeunload
处理器说we have a great offer for you?
,如果用户选择leave the page
,它应该做正常的传播,但如果他选择stay on the page
,我需要他重定向到提供页面redirection is important, no compromise
。为了进行测试,让我们重定向到google.com
我做了一个程序,如下所示-
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
但问题是,如果他点击yahoo.com
的链接并选择leave the page
,他不会去雅虎,而是去谷歌:
救救我!提前感谢
发布于 2013-05-30 05:27:34
最好在本地查一查。
查看评论并尝试这样做:
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
并将您的html代码更改为:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
<a href="http://yahoo.com">try it</a>
</body>
发布于 2013-05-30 07:36:47
在解决这个问题一段时间后,我做了以下操作。它似乎是有效的,但它不是很可靠。最大的问题是,超时功能需要桥接足够长的时间跨度,以便浏览器连接到链接的href属性中的url。
jsfiddle to demonstrate。因为google.com,我使用了X-Frame-Options: SAMEORIGIN
而不是bing.com
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
发布于 2013-06-05 16:54:24
试试following,(添加了一个全局函数,可以随时检查状态)。
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
https://stackoverflow.com/questions/16695886
复制相似问题