在 Javascript 中,是否有一种技术可以监听标题元素的变化?
如何监听标题元素的变化?
IT技术
javascript
dom-events
                    2021-03-05 20:16:00
                
                    
                
            
        6个回答
            5 年后,我们终于有了更好的解决方案。使用MutationObserver!
简而言之:
new MutationObserver(function(mutations) {
    console.log(mutations[0].target.nodeValue);
}).observe(
    document.querySelector('title'),
    { subtree: true, characterData: true, childList: 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, childList: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
此外突变观察员真棒浏览器支持:

您可以在大多数现代浏览器中对事件执行此操作(值得注意的例外是所有版本的 Opera 和 Firefox 2.0 及更早版本)。在 IE 中,您可以使用propertychange事件,document在最近的 Mozilla 和 WebKit 浏览器中,您可以使用通用DOMSubtreeModified事件。对于其他浏览器,您将不得不退回到 polling document.title。
请注意,我无法在所有浏览器中对此进行测试,因此您应该在使用前仔细测试。
2015 年 4 月 9 日更新
Mutation Observers 是当今大多数浏览器的首选方式。参见 Vladimir Starkov 的回答示例。您可能希望将以下一些内容作为旧浏览器(例如 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();
            }
        };
    }
};
没有内置事件。但是,您可以使用以下方法setInterval来完成此操作:
var oldTitle = document.title;
window.setInterval(function()
{
    if (document.title !== oldTitle)
    {
        //title has changed - do something
    }
    oldTitle = document.title;
}, 100); //check every 100ms
这是我的方式,关闭并检查启动
(function () {
    var lastTitle = undefined;
    function checkTitle() {
        if (lastTitle != document.title) {
            NotifyTitleChanged(document.title); // your implement
            lastTitle = document.title;
        }
        setTimeout(checkTitle, 100);
    };
    checkTitle();
})();
不要忘记在不再需要时删除侦听器。
香草JS:
const observer = new MutationObserver((mutations) => {
     console.log(mutations[0].target.text);
});
observer.observe(document.querySelector("title"), {
  subtree: true,
  characterData: true,
  childList: true,
})
observer.disconnect() // stops looking for changes
或者,如果你使用 React 删除监听器非常简洁,我写了这个钩子:
React.useEffect(() => {
    const observer = new MutationObserver(mutations => {
       console.log(mutations[0].target.text)
    })
    observer.observe(document.querySelector("title"), {
        subtree: true,
        characterData: true,
        childList: true,
    })
    return () => observer.disconnect()
}, [defaultTitle, notificationTitle])
其它你可能感兴趣的问题