joe*_*lpt 13 javascript jquery webkit google-chrome-extension
有没有办法检测到document.title/ head > title通过Javascript 的更改?我想通过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';
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
joe*_*lpt 31
我找到了一个完全有效的解决方案,这只是我在原帖中发布的示例的一个小修改.
// 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
Run Code Online (Sandbox Code Playgroud)
添加的subtree: true是需要得到这个工作的权利所有.
最后在setTimeout电话中包含三种改变标题的方法仅用于演示目的; 如果没有这个,标题值的变化会很快,以至于WebKitMutationObserver不会单独报告每个更改,因为MutationObserver旨在在执行观察者回调之前的短时间内累积更改.
如果不需要检测通过最后一个jQuery-only方法进行的标题更改,则childList: true可以从该observer.observe行中省略该属性; 只characterData: true需要检测前两个改变标题的方法.
| 归档时间: |
|
| 查看次数: |
7622 次 |
| 最近记录: |