在javascript中,有没有一种技术可以监听对title元素的更改?
5年后,我们终于有了更好的解决方案。使用MutationObserver!
简而言之:
new MutationObserver(function(mutations) {
console.log(mutations[0].target.nodeValue);
}).observe(
document.querySelector('title'),
{ 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 = { childList: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
您可以通过大多数现代浏览器中的事件来执行此操作(值得注意的例外是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();
}
};
}
};
没有内置事件。但是,您可以使用setInterval
完成此操作:
var oldTitle = document.title;
window.setInterval(function()
{
if (document.title !== oldTitle)
{
//title has changed - do something
}
oldTitle = document.title;
}, 100); //check every 100ms
这是我的方法,在关闭并启动时检查
(function () {
var lastTitle = undefined;
function checkTitle() {
if (lastTitle != document.title) {
NotifyTitleChanged(document.title); // your implement
lastTitle = document.title;
}
setTimeout(checkTitle, 100);
};
checkTitle();
})();