title: Javascript / jQuery: delete iframe after contentWindow.print
body: <p>I'm using this code, which has stemmed from <a href="https://stackoverflow.com/questions/5220249/print-from-frontend-javascript">here</a> and <a href="https://stackoverflow.com/questions/4689145/pass-jquery-variables-between-iframe-and-parent/4689154#4689154">here</a>.</p>
  
  <pre><code>$('#my_button').on('click', function (e) {
      var iframe = document.createElement('iframe');
      iframe.id = "my_iframe";
      iframe.onload = function() {
          var doc = iframe.contentDocument || iframe.contentWindow.document;
          doc.getElementsByTagName('body')[0].innerHTML = "&lt;p&gt;test123&lt;/p&gt;";
  
          iframe.contentWindow.focus(); 
          iframe.contentWindow.print();
  
          $("#my_iframe", top.document).remove();
      };
  
      document.getElementsByTagName('body')[0].appendChild(iframe);
  });
  </code></pre>
  
  <p>Without the <code>remove</code> line, it prints fine. However, the <code>remove</code> line removes the <code>iframe</code> before it has a chance to execute the <code>print()</code>. How can I set up some kind of callback so that it prints and only then removes the iframe?</p>
  
  <p>Thanks.</p>