title: How to attach submit listener to all forms including those in iframes and nested iframes
body: <p>I want to attach an event listener to every form on my site so that when a form is submitted, a confirm box will pop up asking if the user is sure they want to proceed.  If the user is not sure, I don't want the form to fire.</p>
  
  <p>So far I have this code:</p>
  
  <pre><code>window.onload = function() {
    for(var i=0; i&lt;document.forms.length; i++){
      document.forms[i].addEventListener("submit",formSubmit,false);
    }
  }
  
  function formSubmit(e) {
    if (confirm("Are you sure?")) {
      return true;
    }
    return false;
  }
  </code></pre>
  
  <p>Notes:</p>
  
  <ol>
  <li>I can't use jQuery</li>
  <li>I can't use an onDOMReady type function because the iframes may not have loaded yet - so <code>window.onload</code> is my only option (I think?)</li>
  <li>This code does not work because when the "Are you sure?" confirm box pops up when I submit a form, whichever button I click, the form still submits.</li>
  <li>This code also does not work because it does not pick up forms inside iframes.  I need to not only catch forms within iframes, but also forms that may be within iframes that are within iframes...</li>
  </ol>
  
  <p>I've tried this:</p>
  
  <pre><code>var frame = document.getElementById("frameID").contentDocument;
  for(var i=0; i&lt;frame.forms.length; i++){
    frame.forms[i].addEventListener("submit",formSubmit,false);
  }
  </code></pre>
  
  <p>But it only works for the first frame, and it doesn't seem to work if I have got to the page via the "Back" button.  Is that something to do with the way <code>wondow.onload</code> works?</p>
  
  <p>Thanks for your help in advance!</p>
  
  <p><strong>Update</strong></p>
  
  <p>From the answer given by @Jan Pfeifer I have the following code which solves the problem of the form still submitting even when you choose "Cancel", but it does not add the listener to every form in every frame properly.  I'm starting a bounty for this - can anyone make it work for nested iframes in every browser?</p>
  
  <pre><code>function attach(wnd,handler){
    for(var i=0; i&lt;wnd.document.forms.length; i++){
      var form = wnd.document.forms[i];
      form.addEventListener('submit',handler,false);
    }
  
    for(var i=0; i&lt;wnd.frames.length; i++){
      var iwnd = wnd.frames[i];               
      attach(iwnd,handler);
    }
  }
  
  function formSubmit(e){
    if(!confirm('Are you sure?')) {
      e.returnValue = false;
      if(e.preventDefault) e.preventDefault();
      return false;
    }
    return true;
  }
  
  window.addEventListener('load',function(){attach(window,formSubmit);},false);
  </code></pre>