How to listen for changes to the title element?

后端 未结 4 1863
渐次进展
渐次进展 2020-12-01 05:18

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

4条回答
  •  自闭症患者
    2020-12-01 06:06

    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:

提交回复
热议问题