Search code examples
javascriptlocationuridocumentmailto

mailto uri - javascript window.open and then close, still stays open in < IE8


function SendInfo(href) {
    var subject= "Some information";
    var body = "I thought you might find this information interesting:\r\n\r\n<";
    body += document.location;
    body += ">";
    var uri = "mailto:?subject=";
    uri += encodeURIComponent(subject);
    uri += "&body=";
    uri += encodeURIComponent(body);
    win = window.open(uri);
    win.close();
}

In FF, Chrome and IE9, the new tab/window closes as it should.

However in IE8 and below, a new window opens and the user gets a security warning.

Is there a better way to approach this to prevent those issues?

jsbin: http://jsbin.com/itazab


Solution

  • It is not optimal to open a window that you need to close. If you did not get a warning you could use setTimeout like this:

    win = window.open(uri);
    setTimeout(function() { win.close();},1000);
    

    Instead I suggest you do this

    function SendInfo(href) {
      var subject= "Some information";
      var body = "I thought you might find this information interesting:\r\n\r\n<";
      body += href; // or document.location;
      body += ">";
      var uri = "mailto:?subject=";
      uri += encodeURIComponent(subject);
      uri += "&body=";
      uri += encodeURIComponent(body);
      return uri;
    }
    
    <a href="#" onclick="this.href=SendInfo(location.href)">Tell a friend</a>