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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16695886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:37:07  来源:igfitidea点击:

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

javascriptjquery

提问by Rohit Agrawal

Rewriting the question -

改写问题——

I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunloadhandeler saying we have a great offer for you?and if user choose to leave the pageit should do the normal propogation but if he choose to stay on the pageI need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com

我正在尝试制作一个页面,如果用户离开页面(到其他链接/网站或关闭窗口/选项卡),我想显示处理onbeforeunload程序说we have a great offer for you?,如果用户选择leave the page它应该进行正常传播,但如果他选择stay on the page我需要他将其重定向到提供页面redirection is important, no compromise。为了测试让我们重定向到google.com

I made a program as follows -

我做了一个程序如下 -

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;

but the problem is that if he click on the link to yahoo.comand choose to leave the pagehe is not going to yahoo but to google instead :(

但问题是如果他点击链接yahoo.com并选择leave the page他不会去雅虎而是去谷歌:(

Help Me !! Thanks in Advance

帮我 !!提前致谢

here is the fiddle code

这是小提琴代码

here how you can test because onbeforeunload does not work on iframe well

在这里你可以如何测试,因为 onbeforeunload 在 iframe 上不能很好地工作

回答by A. Wolff

This solution works in all cases, using back browser button, setting new url in address bar or use links. What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler. In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)

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

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

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

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

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

EDIT:set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!) BTW, using bing.comdue to google not allowing no more content being displayed inside iframe.

编辑:在 codepen 上设置 DEMO,显然 jsFiddle 不喜欢这个片段(?!)顺便说一句,bing.com由于谷歌不允许在 iframe 中显示更多内容而使用。

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

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);
}

回答by Siamak A.Motlagh

It's better to Check it local.
Check out the comments and try this: LIVE DEMO

最好在本地检查一下。
查看评论并尝试此操作: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");
}

And change your html code to this:

并将您的 html 代码更改为:

<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
    <a href="http://yahoo.com">try it</a>
</body>

回答by Bart

After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.

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

jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN

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;

回答by WhyMe

Try the following, (adds a global function that checks the state all the time though).

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

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;});

回答by Tareq

<script>
        function endSession() {
            // Browser or Broswer tab is closed
            // Write code here
            alert('Browser or Broswer tab closed');
        }
</script>

<body onpagehide="endSession();">

回答by Ayyash

I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...

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

Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)

请注意,在您提示用户之前,您已经将 url 的来源更改为 Google,此操作无法撤消...除非可能,您可以将超时设置为 5 秒之类的时间(但是如果用户不够快不会接受他的回答)

Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

编辑:我刚刚让它经过了 5000 次时间流逝,它总是转到 Yahoo! 从来没有拿起谷歌的变化。