Sonntag, 22. März 2015

Create client-side email using mailto before server postback

Problem:
So it looks like it isn't a good idea to set the window.location.href before a postback.

 I tried a few options, like using the setTimeout function to force setting window.location.href slightly later in the JS thread lifecycle. But that didn't work; it seemed that any alteration of the DOM's location was causing issues with the postback.

So how can we get the browser to call the mailto link without affecting the postback?
Use an iframe, as the source of the iframe would be separate from the current document and should not interfere with any postbacks.
I modified my CreateEmail function so it would create a new iframe with its src attribute set to the mailto link, append it to the document body so the browser would execute the mailto link, and then remove it again from the DOM:
Solution:

<script type="text/javascript">

  function CreateEmail() {
    var mailto =  'mailto:?to=any@anydomain.com';

    $('<iframe />')
       .prop('src', mailto)
       .css('display', 'none')
       .appendTo('body')
       .remove();
  }
</script>

Keine Kommentare:

Kommentar veröffentlichen