Okay, so I was able to get this working in Chrome on Mac. Your mileage may vary. Also, this is pretty hacky IMO, so it may not be worth it. Honestly this should exist as a setting within Chrome, and the behavior should be delegated to the website. E.g. Chrome should have an option: "[x] Always open mailto links in separate tab"
That being said, here's how you do it.
First construct your links like so:
<a href="#" data-mailto="[email protected]">Mail Somebody</a>
Then set a click handler for those.
$('a[data-mailto]').click(function(){
var link = 'mailto.html#mailto:' + $(this).data('mailto');
window.open(link, 'Mailer');
return false;
});
There is an optional options
argument to window.open
that you can tweak. In fact I would almost recommend it, to see if you can get the generated window to be as unnoticable as possible.
https://developer.mozilla.org/en/DOM/window.open
http://www.w3schools.com/jsref/met_win_open.asp (the MDN doc is exhaustive, while the w3schools doc is almost easier to read)
Next we need to create the mailto.html page. Now you may need to play around with the timeout you see below. You could probably even set this to something really short like 500ms.
<html>
<script>
function checkMailto(hash){
hash = hash.split('mailto:');
if(hash.length > 1){
return hash[1];
} else {
return false;
}
}
var mailto = checkMailto(location.hash);
if(mailto){
location.href = 'mailto:'+mailto;
setTimeout(function(){
window.close();
}, 1000);
}
</script>
</html>
Results
Mail.app set as my default email reader:
When I click the link, it opens a window for a split second, then composes a blank message. In the browser it goes back to the original page.
Gmail set as mail reader under Settings > Advanced > Privacy > Handlers:
When I click the link, it opens a new tab to Gmail, with the previous page safely in it's own tab.
Note: Once you set Gmail as your email handler, on the OS side (at least on mac), Chrome is set as the system's email handler. So even if you turn off Gmail as the email handler inside Chrome, it is still set on the OS level. So to reset that, I went to Mail > Prefs > General. And set default mail reader back to Mail.
foo.com/mailto.html#mailto:[email protected]
How I wanted it to work, would be that if the email handler was gmail, the location.href call would negate thewindow.close()
call. And if the email handler was on the OS, the window would close itself after a delay. Turns out window.close() doesn't actually work in Chrome. Didn't bother testing elsewhere. – Hydraulic