JavaScript: Auto-close "mailto" Window in Browser

Author Avatar
Nathaniel Apr 12, 2017

Recently, I discovered a little glitch on this blog.

When I click “Mail Me” in the dropdown menu in the side bar, the browser opens a new window with the mailto: URL. After the default mail client on the OS is launched, the new window still stays in the browser, and the user has to manually close it.

This is no big issue, but I still wanted to make it better by getting the browser to automatically close this mailto window after the mail client is launched. After some research and experiement, I finally came up with an idea that works.

Let’s assume what we originally have in the dropdown menu list is something like:

<li>
<a href="mailto:[email protected]" target="_blank" title="Email Me">
Email Me
</a>
</li>

According to the code above, when the user clicks the <a> element, the browser will open a new window and launch the mail client. Now that we want the browser to automatically close the new window, a few changes have to be made.

First, add a segment of JavaScript code into the HTML file:

<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function launchMailClient(address){
var w = window.open("mailto:" + address);
await sleep(500);
w.close();
}
</script>

There are two functions in the snippet above:

  • sleep(): make the thread sleep for a certain number of milliseconds.
  • launchMailClient(): open a new window with the mailto: url, wait for 0.5 second, and close it.

Second, update the original HTML code:

<li onclick="launchMailClient('[email protected]')">
<a href="javascript:void(0)">
Email Me
</a>
</li>

That’s it. When the user gets back to the browser after sending the email, there will be no more annoying mailto: window.