How to use MutationObserver in a new window

I want to use MutationObserver to track DOM changes in a window that I create with window.open. I have the following code:

var newWin = window.open('/somepath');
var observerConfig = {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
};
var obs = new newWin.MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (!mutation.addedNodes) return;
        mutation.addedNodes.forEach(function(addedNode) {
            console.log(addedNode);
        });
    })
});
obs.observe(newWin.document, observerConfig);

I expected to see some recently added nodes registered in the console (as I understand it, when I tracked the original window the same way, the same observer), but I get nothing. Did I miss something?

+4
source share
1 answer

This is the same problem you encountered when using JavaScript (e.g. from script in <head>) to change the DOM of the current document before loading the DOM: you are trying to access elements that do not currently exist in memory.

DOMContentLoaded, , DOM .

, DOM , , , .

obs.observe load:

newWin.addEventListener('load', function() {
    obs.observe(newWin.document.body, observerConfig);
}, true);

, , , !

+2

Source: https://habr.com/ru/post/1691583/


All Articles