title: How to override JavaScript alert function inside an iframe before it finished loading?
body: <p>I am using <strong>headless chrome browser</strong> with wraith(<a href="https://github.com/BBC-News/wraith" rel="nofollow noreferrer">https://github.com/BBC-News/wraith</a>). The <strong>problem</strong> is when I have a page that opens an <strong>alert</strong> wraith fails</p>
  
  <pre><code>ERROR: unexpected alert open: {Alert text : Bla bla bla.}
    (Session info: headless chrome=71.0.3578.98)
    (Driver info: chromedriver=71.0.3578.33 (269aa0e3f0db08097f0fe231c7e6be200b6939f7),platform=Mac OS X 10.13.6 x86_64)
  </code></pre>
  
  <p>This is what I tried, but has failed so far:</p>
  
  <pre><code>const BACKEND_USERNAME = "";
  const BACKEND_PASSWORD = "";
  
  function resizeIFrameToFitContent(iFrame) {
      iFrame.width = iFrame.contentWindow.document.body.scrollWidth;
      iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
  }
  
  
  var original_url_asked = document.referrer;
  if (typeof jQuery !== 'undefined') {//maybe 500 or 404 page
      $(document).ready(function () {
          //we ended up on login page, let's login
          $('body &gt; div:nth-child(23) &gt; div.backend_right_content &gt; div &gt; div &gt; form &gt; input[type="password"]:nth-child(3)').prop('value', BACKEND_PASSWORD);
          $('body &gt; div:nth-child(23) &gt; div.backend_right_content &gt; div &gt; div &gt; form &gt; input[type="text"]:nth-child(1)').prop('value', BACKEND_USERNAME);
          $('body &gt; div:nth-child(23) &gt; div.backend_right_content &gt; div &gt; div &gt; form &gt; input[type="submit"]:nth-child(5)').click();//submit form
  
          //we are logged in
          $('body').empty();//clear all the stuff
          //since we can't redirect, we'll open a full page iframe with the url we wanted to see initially
          $('body').append('&lt;iframe id="ifr" width="100%" height="100%" frameborder="0" src="" &gt;&lt;/iframe&gt;');
  
          //load the original_url finally
          $("#ifr").attr("src", original_url_asked);//cannot redirect or wraith complains
  
  
          //hide the menu and other elements, for smaller screenshots
          $('#ifr').on('load', function () {
              $('#ifr').contents().find('div.backend_left, div.backend_right_top').remove();
              resizeIFrameToFitContent(document.getElementById('ifr'));
          });
      });
  }
  
  //important or wraith will not understand it is ready to take a screenshot
  var callback = arguments[arguments.length - 1];
  setTimeout(callback, 20000);//wait for page to load
  </code></pre>