Skip to content
Advertisement

How to listen for changes to the title element?

In Javascript, is there a technique to listen for changes to the title element?

Advertisement

Answer

5 years later we finally have a better solution. Use MutationObserver!

In short:

new MutationObserver(function(mutations) {
    console.log(mutations[0].target.nodeValue);
}).observe(
    document.querySelector('title'),
    { subtree: true, characterData: true, childList: true }
);

With comments:

// select the target node
var target = document.querySelector('title');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    // We need only first event and only new value of the title
    console.log(mutations[0].target.nodeValue);
});

// configuration of the observer:
var config = { subtree: true, characterData: true, childList: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

Also Mutation Observer has awesome browser support:

Advertisement