iframe behaviour of onload vs addEventListener('load')

前端 未结 3 1832
南旧
南旧 2021-02-01 06:32

I\'ve been playing around with adding hidden iframe elements to a page, and I want to manipulate the DOM of the these once loaded. I\'ve noticed that I can\'t start manipulating

3条回答
  •  长发绾君心
    2021-02-01 06:51

    This is working for me:

    html:

    iframe source code: 

    javascript (on documentReady):

    var iframe = document.createElement('iframe');
    iframe.id = iframe.name = "testframe";
    iframe.src = "http://fiddle.jshell.net";
    iframe.width = 400;
    iframe.height = 100;
    iframe.style.display = "none";
    
    if (iframe.addEventListener)
        iframe.addEventListener("load", loaded, false);
    else
        iframe.attachEvent("onload", loaded);
    
    function loaded() {
        var html;
        if (iframe.contentDocument)
            html = iframe.contentDocument.getElementsByTagName("HTML")[0].innerHTML;
        else
            html = window.frames[iframe.name].document.getElementsByTagName("html")[0].innerHTML;
    
        document.getElementById("output").value = html;
    }
    
    document.getElementsByTagName("body")[0].appendChild(iframe);
    

    See the Demo at: http://jsfiddle.net/WcKEz/

    Works with addEventListener, but includes the fallback to attachEvent. Access to the DOM of the IFRAME of course only on the same domain.

提交回复
热议问题