通过Javascript检测文档标题的更改

有没有办法通过Javascript检测对document.title / head > title的更改? 我希望通过Google Chrome扩展程序内容脚本检测到这一点,因此我无法在目标页面的JS中实际连接执行标题更改的代码。

我发现WebKitMutationObserver理论上应该能够检测到head > title的更改,但它并不适用于所有情况:

 // set up an observer for the title element var target = document.querySelector('title'); var observer = new WebKitMutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation); }); }); var config = { attributes: true, childList: true, characterData: true }; observer.observe(target, config); // this jQuery statement fires the observer as expected ... $('head > title').text('foo'); // ... but this doesn't: document.querySelector('title').innerText = 'cheezburger'; // ... and neither does this: document.title = 'lorem ipsum'; 

有任何想法吗?

我找到了一个完全有效的解决方案,这只是我在原帖中发布的示例的一个小修改。

 // set up an observer for the title element var target = document.querySelector('head > title'); var observer = new window.WebKitMutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log('new title:', mutation.target.textContent); }); }); observer.observe(target, { subtree: true, characterData: true, childList: true }); // all three of these methods correctly fire the mutation observer setTimeout(function() { document.title = 'foo'; }, 1000); // the usual method setTimeout(function() { document.querySelector('head > title').innerText = 'bar'; }, 2000); // DOM method setTimeout(function() { $('head > title').text('cheezburger'); }, 3000); // jQuery-only method 

增加subtree: true就是使这个工作正常所需的全部内容。

最后在setTimeout调用中包装三个标题更改方法仅用于演示目的; 如果没有这个,标题值变化太快,以至于WebKitMutationObserver不会单独报告每个更改,因为MutationObserver旨在在执行观察者回调之前的短时间内累积更改。

如果不需要检测通过最后一个jQuery-only方法进行的标题更改,则可以从observer.observe行中省略childList: true属性; 只需要characterData: true即可检测前两个标题更改方法。

您的代码示例中包含JQuery和Javascript。 不确定你是否仅限于JavaScript,但这里是你如何用jQuery做到的

如果您想触发更改,请查看: http : //api.jquery.com/trigger/

jQuery的

 $(document).ready(function () { $("title", "head").change(function () { console.log("Title has changed"); }); //Trigger Change $("title","head").text("New Title").trigger("change"); });