mailto链接(在chrome中)触发window.onbeforeunload - 我可以阻止这个吗? [英] mailto link (in chrome) is triggering window.onbeforeunload - can i prevent this?

查看:112
本文介绍了mailto链接(在chrome中)触发window.onbeforeunload - 我可以阻止这个吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能与如何在不创建新标签的情况下使用Window.open在Chrome中打开mailto链接?

大家好。我有一个表单页面,我放了一个window.onbeforeunload确认,以阻止人们导航并意外丢失他们的更改:

Hi all. I have a form page where i've put a window.onbeforeunload confirm, to stop people navigating away and losing their changes by accident:

window.onbeforeunload = function(){
  if(changed)
    return "You have unsaved changes.  Do you really want to leave this page without saving?";
};  

其中已更改是我设置为的变量每当用户进行任何更改时为true。那一切都很好。但是,我还添加了一些指向页面的mailto链接,如下所示:

where changed is a variable i set to true whenever the user makes any changes. That's all fine. However, i've also added some mailto links to the page, like so:

<a class="button button-alt" href="mailto:foo@foo.com">Report a problem</a>

即使mailto没有离开页面(它正在打开用户默认邮件应用程序) ,它仍然触发onb​​eforeunload事件,提示确认框,这很烦人。我可以在链接上设置 target =_ blank,然后用户将坐在空白标签中。

Even though the mailto isn't navigating away from the page (it's opening the users default mail app), it's still triggering the onbeforeunload event, prompting the confirm box, which is annoying. I can get round it setting target="_blank" on the link, but then the user is left sitting in an empty tab.

我可以将mailto链接设置为不触发onb​​eforeunload事件吗?我想到了一个可怕的hacky方式,通过使用另一个临时的javascript变量,导致onbeforeunload确认不触发,但它似乎有点脏。无论如何,我会在等待回复但是有人有更好的解决方案吗?

Can i set the mailto link to not trigger the onbeforeunload event? I thought of a horribly hacky way of doing it by having another temporary javascript variable which causes the onbeforeunload confirm to not trigger, but it seems kind of dirty. I'll do it anyway while i wait for a response but does anyone have a nicer solution?

谢谢,最大

推荐答案

基于epascarello的解决方案,以下JQuery代码可以解决这个问题:

Building off of epascarello's solution, the following JQuery code should do the trick:

    var ignore_onbeforeunload = false;
    $('a[href^=mailto]').on('click',function(){
        ignore_onbeforeunload = true;
    });

    window.onbeforeunload = function() {
        if (!ignore_onbeforeunload){
            return "Halt! you are not supposed to leave!";
        }
        ignore_onbeforeunload = false;
    };

这篇关于mailto链接(在chrome中)触发window.onbeforeunload - 我可以阻止这个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆