使用onbeforeunload事件,在选择留在此页面时更改url

using onbeforeunload event, url change on selecting stay on this page

本文关键字:url 事件 onbeforeunload 选择 使用      更新时间:2023-09-26

改写问题-

我正在尝试制作一个页面,如果用户离开页面(无论是到其他链接/网站或关闭窗口/选项卡),我想显示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,他不是去雅虎,而是去谷歌:(

救救我!!提前感谢

这里是小提琴代码

这里如何测试,因为onbeforeunload不工作在iframe

此解决方案适用于所有情况,使用后退浏览器按钮,在地址栏设置新url或使用链接。我发现的是触发onbeforeunload处理程序不显示附加到onbeforeunload处理程序的对话框。在这种情况下(当需要触发时),使用确认框来显示用户消息。此解决方案在chrome/firefox和IE(7到10)中进行了测试

罢工罢工

<> http://jsfiddle.net/W3vUB/4/show

罢工罢工

<> http://jsfiddle.net/W3vUB/4/

EDIT: set DEMO on codepen,显然jsFiddle不喜欢这个片段(?!)顺便说一句,使用bing.com由于谷歌不允许没有更多的内容显示在iframe内。

http://codepen.io/anon/pen/dYKKbZ

var a, b = false,
    c = "http://bing.com";
function triggerEvent(el, type) {
    if ((el[type] || false) && typeof el[type] == 'function') {
        el[type](el);
    }
}
$(function () {
    $('a:not([href^=#])').on('click', function (e) {
        e.preventDefault();
        if (confirm("Do you really want to leave now?")) c = this.href;

        triggerEvent(window, 'onbeforeunload');
    });
});
window.onbeforeunload = function (e) {
    if (b) return;
    a = setTimeout(function () {
        b = true;
        window.location.href = c;
        c = "http://bing.com";
        console.log(c);
    }, 500);
    return "Do you really want to leave now?";
}
window.onunload = function () {
    clearTimeout(a);
}

最好在本地检查。
查看注释并尝试这个:LIVE DEMO

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>

在解决了这个问题一段时间后,我做了以下操作。它似乎有用,但不太可靠。最大的问题是超时函数需要桥接足够大的时间跨度,以便浏览器连接到链接的href属性中的url。

jsfield来演示。因为X-Frame-Options: SAMEORIGIN

我用bing.com代替google.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;

尝试以下操作,(添加一个全局函数,始终检查状态)

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;});
<script>
        function endSession() {
            // Browser or Broswer tab is closed
            // Write code here
            alert('Browser or Broswer tab closed');
        }
</script>
<body onpagehide="endSession();">

我想你对事件的进展感到困惑,在卸载页面之前仍然在交互,返回方法就像返回"confirm()"的快捷方式,但是确认的返回根本不能处理,所以你不能真正调查用户的响应并决定走哪条路,响应将立即执行为"yes"离开页面,或"no"不离开页面…

注意,在你提示用户之前,你已经将url的来源更改为Google,这个动作,不能撤消…除非,你可以将超时设置为5秒(但如果用户不够快,它就不会接收到他的答案)

编辑:我刚刚把它设置为5000延时,它总是去雅虎!根本不接受google的改变