有什么方法可以通过 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
来检测前两个标题更改方法。