Search code examples
javascriptasynchronouswindow.openmutation-observers

How to use MutationObserver on a newly created window


I want to use MutationObserver to track DOM changes in a window 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 would expect to see some newly added nodes logged in the console (as I got when I tracked the original window the same way, same observer), but I get nothing. Am I missing something?


Solution

  • This is the same problem you would face when using JavaScript (from a script in <head> for instance) to modify the DOM of the current document, before the DOM has been loaded: you would be trying to access elements that do not exist in memory at this time.

    You would use the DOMContentLoaded event to trigger a callback when the DOM has been loaded and is ready to manipulate.

    Similarly, when you are trying to access the DOM of the new window, that window may not have finished loading yet.

    You should wrap your obs.observe call in a load event listener:

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

    This way when you begin observing the body you are sure that it actually exists!