Reputation: 1957
I have a web page that creates a list of contacts and their email addresses. You have two options for the mailto link, (1) open it in the current window or (2) open it in a new tab/window.
I see potential drawbacks from both sides:
Is there anyway to "detect" if the opened webpage has content and close it if not?
Based on this link:
Detecting web-based mail client vs local mail client for a mailto link
I tried the following to get the body
:
const windowRef = window.open(`mailto:${email}`, '_blank')
const body = windowRef.document.body
The problem I was running into was that the body
of each document was empty: <body></body>
I assume this was because it didn't have enough time to load the page, so I attempted to setTimeout
but then I got a Blocked a frame with origin "myhostman" from accessing a cross-origin frame.
Any ideas on a way to support both web and desktop mail clients without the drawbacks listed above?
Upvotes: 6
Views: 3062
Reputation: 451
This is pretty kludgy, but it might do what you need:
You can have a SendEmail()
function defined like this:
function SendEmail() {
const windowRef = window.open(`mailto:[email protected]`, '_blank');
windowRef.focus();
windowRef.onfocus = function() {
return;
}
setTimeout(function(){
windowRef.close();
},500);
}
and your html
looks something like this:
<a href="javascript:void(0)" onclick="SendEmail();">email</a>
The idea behind this is that, if your user has a webmail as their default email client, then the function
will just exit; however, if the user has a desktop email client, the new window will lose focus triggering the setTimeout()
closing the new opened window.
My test works well using this JSFiddle but is "half" tested, I mean, since I don't have a webmail client set as my default client, I can't confirm this will actually work as you want, however I can confirm that the window closed when my desktop email client opened...
UPDATE:
Forget the function above, I slightly modified it to this:
function SendEmail() {
const windowRef = window.open(`mailto:[email protected]`, '_blank');
windowRef.focus();
setTimeout(function(){
if(!windowRef.document.hasFocus()) {
windowRef.close();
}
}, 500);
}
I tested this in Firefox by setting Gmail and Yahoo! as my default email clients, and the new opened tab remained opened; then I changed it back to my desktop email client, and the new opened tab closed. I did the same test using Vivaldi, and IE Edge (where my desktop client is set as the default one), and the results were successfully the same. Here's the updated JSFiddle.
Upvotes: 9