Why can't observe document.write on document.body using MutationObserver API?

泄露秘密 提交于 2020-01-24 09:46:25

问题


I failed to observe document.write on document.body. Here is code:

<script>
var observeDOM = (function(){
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
        eventListenerSupported = window.addEventListener;

    return function(obj, callback){
        if( MutationObserver ){
            // define a new observer
            var obs = new MutationObserver(function(mutations, observer){
                if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
                    callback();
            });
            // have the observer observe foo for changes in children
            obs.observe( obj, { childList:true, subtree:true });
        }
        else if( eventListenerSupported ){
            obj.addEventListener('DOMNodeInserted', callback, false);
            obj.addEventListener('DOMNodeRemoved', callback, false);
        }
    }
})();

window.onload = function() {
    //console.log("dom ready");

    // Observe a specific DOM element:
    observeDOM( document.body ,function(){ 
        console.log('dom changed');
    });
}

function reload() {
    document.write("<input type=\"submit\" onclick=\"reload();\" value=\"Reload\" />");

    //var text = document.createTextNode("abc");
    //document.body.appendChild(text);
}
</script>
<body>
<input type="submit" onclick="reload();" value="Reload" />
</body>

When I click Reload button, nothing logged. But if I change code in window.onload to:

observeDOM( document ,function(){ // change first parameter to *document*
    console.log('dom changed');
});

And then click Reload, console outputs dom changed. Could anyone tell why? I'm using Chrome v50.


回答1:


I find the reason today. It seems that document.write() covers old document.body with a new one. Since MutationObserver was attached to old document.body, it can't observe DOM change on new body.

Here is how I tested it:



来源:https://stackoverflow.com/questions/37110926/why-cant-observe-document-write-on-document-body-using-mutationobserver-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!