Javascript 如何侦听title元素的更改?

Javascript 如何侦听title元素的更改?,javascript,dom-events,Javascript,Dom Events,在Javascript中,是否有监听title元素更改的技术?没有内置事件。但是,您可以使用setInterval来完成以下操作: var oldTitle = document.title; window.setInterval(function() { if (document.title !== oldTitle) { //title has changed - do something } oldTitle = document.title

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

没有内置事件。但是,您可以使用
setInterval
来完成以下操作:

var oldTitle = document.title;
window.setInterval(function()
{
    if (document.title !== oldTitle)
    {
        //title has changed - do something
    }
    oldTitle = document.title;
}, 100); //check every 100ms

您可以在大多数现代浏览器中使用事件来实现这一点(值得注意的例外是所有版本的Opera和Firefox 2.0及更早版本)。在IE中,您可以使用
document
propertychange
事件,在最近的Mozilla和WebKit浏览器中,您可以使用generic
domsubtreemedited
事件。对于其他浏览器,您必须返回轮询
document.title

请注意,我无法在所有浏览器中测试这一点,因此在使用它之前应该仔细测试

2015年4月9日更新
变异观察者是当今大多数浏览器的发展方向。例如,见弗拉基米尔·斯塔科夫的回答。您可能需要以下一些作为旧浏览器(如IE)的后备,这是我的方式,在关闭和签入启动时

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

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

简言之:

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);
此外:
当不再需要侦听器时,不要忘记删除它

香草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])
const observer=newmutationobserver(([{target}])=>
//日志更改
console.log(target.text),
)
观察者(document.querySelector('title'){
儿童名单:是的,
})

没错。不幸的是,在这种情况下,轮询是唯一的选择。如果没有事件,监听是不可能的(除非javascript对标题进行任何更改,否则也会执行回调)。Gecko浏览器支持监视功能,您可以在其中监视和拦截属性更改。在IE中,我认为有一种onpropertychange或类似的方法可以使用。答案是肯定的,但使用对象推理,假设所有支持addEventListener的浏览器也支持DOMSubtreeModified,并且任何其他浏览器都支持onpropertychange。@RobG:是的,我想是这样。为了简洁起见,在这方面我偶尔会有点懒,因为我的答案是堆栈溢出的。在这种情况下,我认为推论并不太糟糕:
addEventListener
和DOM突变事件都是DOM级别2,在这两个分支中,缺少浏览器支持不会引发错误或造成任何伤害。我认为无法可靠地检测浏览器是否支持检测对标题的更改。可能需要设置侦听器,修改标题,查看是否发生合适的事件,然后还原标题。请在我的中查看modern solutionanswer@VladimirStarkov:是的,在现代浏览器中,突变观察者绝对是一种选择。我建议进行功能测试以获得支持,并将上面的一些功能用作旧浏览器的后备功能。看起来很棒,但当我直接设置document.title:
document.title='test'时,它不起作用
作为一种解决方法,您可以添加:
document.\u定义设置(title',函数(val){document.querySelector('title').childNodes[0].nodeValue=val;})。不幸的是,这可能不适用于所有浏览器。当我直接设置
document.title
时,它也不适用于我。(我使用了Chrome52。)但是,将
childList:true
添加到config对象中修复了它。
newmutationobserver(function(){console.log(document.title);})它可以工作
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])