简体   繁体   中英

mailto link (in chrome) is triggering window.onbeforeunload - can i prevent this?

Possibly related to How to open mailto link in Chrome with Window.open without creating a new tab?

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?";
};  

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>

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.

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?

thanks, max

A really simple fix to this is to do something like this:

<a href="mailto:foo@bar.com" target="hidden-iframe">Email me</a>
<iframe name="hidden-iframe" style="visibility:hidden;position:absolute;"></iframe>

(And of course, move the styles to their own stylesheet instead of inlining them.)

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

I managed to solve this problem inside the onbeforeunload event by checking event.target. This way you dont have to use outer variables or any extra bindings.

window.onbeforeunload = function (event) {

    var activeElement = $(event.target.activeElement);
    // console.log('onbeforeunload', activeElement);

    var isMailto = activeElement && activeElement.is('[href^=mailto:]');
    var isTel = activeElement && activeElement.is('[href^=tel:]');

    if(!isMailto && !isTel) {
        // logic when link is "normal"
    }
};

Add a flag and see if it is flipped, set the flag on the link click.

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

And the link

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

It would be better to add the onclick with JavaScript code.

Another option, also a bit hacky but a bit more generic way to make the beforeunload ignore certain types of links:

In the beforeunload, inspect the link that caused the beforeunload, and if it is not a http or https link, don't bother the user.

Unfortunately it is not easy to inspect the link that caused the beforeunload, so this is where it gets a little hacky with an onclick handler and global variable.

var lastClicked = null;
window.onclick = function(e){
    e = e || window.event;
    lastClicked = e.target
}
window.onbeforeunload = function(e){
    if (changed && lastClicked && lastClicked.href 
        && lastClicked.href.substring(0,4) == 'http')
        return "You have unsaved changes";
}

Edit: Almost forgot, this answer comes from here: https://stackoverflow.com/a/12065766/421243

Some other solution with pure JS and using the focused element:

window.addEventListener("beforeunload", () => {
  const isMailTo = document.activeElement.protocol === "mailto:";

  if (!isMailTo) {
    // do your stuff
  }
});

根据John Kurlak 的回答,您可以简单地使用:

<a href="mailto:foo@bar.com" target="_blank">Email me</a>

Based on Theiaz answer, you can add a Boolean global var as protectUnload followed by a regexp to allow all external protocols except links ( http(s) ):

window.onbeforeunload = function (event) {
    return (protectUnload && (typeof document.activeElement.protocol !== "undefined" && /^http(s)?:$/.test(document.activeElement.protocol))) || null; // return null == no confirm
};

It does not prevent for being kick out from the page using location.href but for in that case you can add 1 more boolean to the formula to always be protected for unloading the page (setting it to true before location.href 's new value).

Set the target of the anchor to a hidden iframe burried in the page. <a href="mailto:x@y.com" target="hiddenIframe" .

If the mailto is called via a javascript function (from a button or anchor or whatever) you could even create the iframe on the fly, set its src to the mailto, then remove it in a timeout.

Either way, the current page is not affected, and no need for pop-up tabs or windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM