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 co
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"
}
};
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
}
});
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.)
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
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;
};
Based on John Kurlak answer, you can simply use :
<a href="mailto:foo@bar.com" target="_blank">Email me</a>