Vla*_*kov 44
5年后,我们终于有了更好的解决方案.使用MutationObserver!
简而言之:
new MutationObserver(function(mutations) {
console.log(mutations[0].target.nodeValue);
}).observe(
document.querySelector('title'),
{ subtree: true, characterData: true }
);
Run Code Online (Sandbox Code Playgroud)
评论:
// 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 };
// pass in the target node, as well as the observer options
observer.observe(target, config);
Run Code Online (Sandbox Code Playgroud)
此外突变观察员真棒浏览器支持:

Tim*_*own 19
您可以在大多数现代浏览器中使用事件执行此操作(值得注意的例外是Opera和Firefox 2.0及更早版本的所有版本).在IE中,您可以使用propertychange事件,document在最近的Mozilla和WebKit浏览器中,您可以使用通用DOMSubtreeModified事件.对于其他浏览器,您将不得不回到轮询document.title.
请注意,我无法在所有浏览器中对此进行测试,因此您应该在使用之前仔细测试.
变异观察者是目前大多数浏览器的发展方式.请参阅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();
}
};
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9994 次 |
| 最近记录: |