Search code examples
javascriptgoogle-chromemailto

How to modify mailto link called by javascript to work in Chrome


I have this JavaScript code (within a PHP page) that opens a new window to call a mailto link, then close the new window - this is done to allow the original window to continue it's process and opens an email in the users mail client.

<script language="javascript">
  var win;
  win = window.open("<?php echo $link; ?>" , "Email Window", "width=100,height=100");
  win.close();
</script>

This code works ok on Edge and Firefox, but not Chrome. I have googled about it - most people are saying about handlers, I have checked (the Chrome handlers), the only option is "allow sites to ask to become default handlers for protocols (recommended)".

Enabling or disabling does not fix the issue. I have tested this on a number of PCs.


Solution

  • It makes no sense to open a mailto: link in a browser window. Instead, create an a element, set its href and then click it programmatically

    let link = document.createElement('a')
    // link.href = '<?= $link ?>'
    link.href = 'mailto:johndoe@example.com'
    link.click()