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

IT技术 javascript jquery
2021-02-24 09:28:35

改写问题——

我正在尝试制作一个页面,如果用户离开该页面(到其他链接/网站或关闭窗口/选项卡),我想显示处理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 上不能很好地工作

6个回答

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

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

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

编辑:在 codepen 上设置 DEMO,显然 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);
}
请注意,Firefox 不会为 onbeforeunload 对话框显示自定义消息。它始终显示默认消息。
2021-04-24 09:28:35
2021-04-30 09:28:35
@Riateche 真的!OP 告诉他这对他来说不是问题。请参阅有问题的评论。
2021-05-05 09:28:35
单击 tryit 然后离开该页面应该转到 yahoo 但它会转到 google
2021-05-10 09:28:35
我如何在离开页面按钮时执行功能一切都很好但是我如何在离开页面按钮时触发事件
2021-05-12 09:28:35

最好在本地检查一下。
查看评论并尝试此操作: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>
它没有在 Firefox 中为我打开任何确认块
2021-04-20 09:28:35
如果用户离开页面(到其他链接/网站或关闭窗口/选项卡),单击将无法解决我的问题,抱歉
2021-04-21 09:28:35
@RohitAgrawal 在 Firefox 中更好地再次检查答案。
2021-04-21 09:28:35
@RohitAgrawal 你在 Firefox 中测试过吗?如果您尝试关闭窗口并且不同意关闭窗口的确认(接受提议)。您将重定向到 google.com。
2021-04-24 09:28:35
如果我尝试使用地址栏或关闭窗口更改 url,则不会出现警报
2021-05-15 09:28:35

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

jsfiddle 来演示我使用 bing.com 而不是 google.com 因为X-Frame-Options: SAMEORIGIN

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;
不可靠的部分 :-) 您需要玩超时毫秒才能获得正确的结果。1400为我工作,但也许您需要将其设置为更高的值。
2021-04-21 09:28:35
所以我已经做了同样的事情,我需要解决这个问题,如果选择留在页面上以获得更高的value,它将稍后转到 bing.com
2021-04-26 09:28:35
点击尝试,然后离开页面转到 bing.com 而不是 yahoo.com
2021-05-01 09:28:35

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

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;});
没有用,我用你的代码jsfiddle.net/pb7th/20/show点击尝试并说离开页面将导致 google.com 而不是链接 url :(
2021-04-23 09:28:35
仍然是同样的错误,我点击了尝试,然后离开应该转到 yahoo.com 的页面,而是转到 google.com
2021-04-28 09:28:35
您可以只在屏幕上添加一个指示器,它会显示“重定向...秒...”,并且在任何情况下都是如此。(关闭和所有)。希望有帮助。
2021-04-28 09:28:35
如果你增加了很多时间,然后点击 try it 并点击停留在页面上将在 10 秒后转到谷歌,所以使用会认为没有任何操作可以执行,同样的问题我最初与计时器有关
2021-05-06 09:28:35
这是一个时间问题。我在 jquery 中重写了整个事情。希望现在它每次都对我有用......你可以改变等待 10 秒的时间,并且可能会让它更加鲁棒...... jsfiddle.net/pb7th/41
2021-05-08 09:28:35
<script>
        function endSession() {
            // Browser or Broswer tab is closed
            // Write code here
            alert('Browser or Broswer tab closed');
        }
</script>

<body onpagehide="endSession();">