Detect DOMContentLoaded in iframe

后端 未结 4 915
天命终不由人
天命终不由人 2020-12-31 07:33

I was surprised to find the following doesn\'t appear to work, insofar as the DOMContentLoaded event doesn\'t fire (this.els is an object of elements).

4条回答
  •  清酒与你
    2020-12-31 07:54

    If your page and the iframe are on the same domain you have to wait for the original page to fire DOMContentLoaded first, then attach a DOMContentLoaded event listener on the iframe's Window (not Document).

    Given you have an iframe as follows,

    
    

    the next snippet will allow you to hook into the iframe's DOMContentLoaded event:

    document.addEventListener('DOMContentLoaded', function () {
        var iframeWindow = frames['iframe-name'];
        // var iframeWindow = document.querySelector('#iframe-id').contentWindow
        // var iframeWindow = document.getElementById('iframe-id').contentWindow
    
        iframeWindow.addEventListener('DOMContentLoaded', function () {
            console.log('iframe DOM is loaded!');
        });
    });
    

提交回复
热议问题