代码之家  ›  专栏  ›  技术社区  ›  jedierikb grijalvaromero

如何监听title元素的更改?

  •  19
  • jedierikb grijalvaromero  · 技术社区  · 15 年前

    在javascript中,是否有监听title元素更改的技术?

    4 回复  |  直到 9 年前
        1
  •  37
  •   eppsilon    9 年前

    5年后,我们终于有了更好的解决方案。使用 MutationObserver !

    简而言之:

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

    评论:

    // 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 };
    
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    

    阿尔索 Mutation Observer has awesome browser support :

        2
  •  17
  •   Tim Down    10 年前

    您可以在大多数现代浏览器中使用事件(Opera和Firefox2.0及更早版本的所有版本都是显著的例外)。你可以用 propertychange 事件 document 在最近的mozilla和webkit浏览器中,您可以使用 DOMSubtreeModified 事件。对于其他浏览器,您将不得不返回到轮询 document.title .

    请注意,我还不能在所有浏览器中测试它,所以在使用之前应该仔细测试它。

    2015年4月9日更新

    如今,在大多数浏览器中,变异观察者都是一种方法。举个例子,看看弗拉基米尔·斯塔科夫的回答。您很可能需要以下内容作为旧版浏览器(如ie<=10和旧版android浏览器)的后备。

    function titleModified() {
        window.alert("Title modifed");
    }
    
    window.onload = function() {
        var titleEl = document.getElementsByTagName("title")[0];
        var docEl = document.documentElement;
    
        if (docEl && docEl.addEventListener) {
            docEl.addEventListener("DOMSubtreeModified", function(evt) {
                var t = evt.target;
                if (t === titleEl || (t.parentNode && t.parentNode === titleEl)) {
                    titleModified();
                }
            }, false);
        } else {
            document.onpropertychange = function() {
                if (window.event.propertyName == "title") {
                    titleModified();
                }
            };
        }
    };
    
        3
  •  3
  •   ShZ    15 年前

    没有内置事件。但是,你可以使用 setInterval 要做到这一点:

    var oldTitle = document.title;
    window.setInterval(function()
    {
        if (document.title !== oldTitle)
        {
            //title has changed - do something
        }
        oldTitle = document.title;
    }, 100); //check every 100ms
    
        4
  •  0
  •   IlPADlI    10 年前

    这是我的方式,在一个关闭和登记启动

    (function () {
        var lastTitle = undefined;
        function checkTitle() {
            if (lastTitle != document.title) {
                NotifyTitleChanged(document.title); // your implement
                lastTitle = document.title;
            }
            setTimeout(checkTitle, 100);
        };
        checkTitle();
    })();