How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

前端 未结 1 1377
走了就别回头了
走了就别回头了 2020-12-13 03:39

Before I paste any code, here\'s the scenario:

  1. I have an HTML document that creates an empty iframe using JavaScript
  2. The JavaScript creates a functio
相关标签:
1条回答
  • 2020-12-13 03:58

    You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

    There's a word for what's happening, possibly "lexical scope": What is lexical scope?

    The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

    This is how I would write it:

    (function () {
      var dom, win, doc, where, iframe;
    
      iframe = document.createElement('iframe');
      iframe.src = "javascript:false";
    
      where = document.getElementsByTagName('script')[0];
      where.parentNode.insertBefore(iframe, where);
    
      win = iframe.contentWindow || iframe;
      doc = iframe.contentDocument || iframe.contentWindow.document;
    
      doc.open();
      doc._l = (function (w, d) {
        return function () {
          w.vanishing_global = new Date().getTime();
    
          var js = d.createElement("script");
          js.src = 'test-vanishing-global.js?' + w.vanishing_global;
    
          w.name = "foobar";
          d.foobar = "foobar:" + Math.random();
          d.foobar = "barfoo:" + Math.random();
          d.body.appendChild(js);
        };
      })(win, doc);
      doc.write('<body onload="document._l();"></body>');
      doc.close();
    })();
    

    The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

    I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

    0 讨论(0)
提交回复
热议问题