In javascript, is there a technique to listen for changes to the title element?
+2
A:
There's not a built-in event. However, you could use setInterval
to accomplish this:
var oldTitle = document.title;
window.setInterval(function()
{
if (document.title !== oldTitle)
{
//title has changed - do something
}
oldTitle = document.title;
}, 100); //check every 100ms
ShZ
2010-03-23 02:35:32
would work, but not quite listening (but polling).
Murali VP
2010-03-23 02:43:58
Yeah, that's true. Unfortunately, polling is the only option in this case. Without an event, listening is impossible (unless whatever javascript changes the title also executes a callback).
ShZ
2010-03-23 02:46:55
Gecko browsers support a watch feature where you can watch for and intercept property changes. In IE I think there is an onpropertychange or similar method you can use.
scunliffe
2010-03-23 02:50:53
+2
A:
You can do this with events in most modern browsers (notable exceptions being all versions of Opera and Firefox 2.0 and earlier). In IE you can use the propertychange
event of document
and in recent Mozilla and WebKit browsers you can use the generic DOMSubtreeModified
event. For other browsers, you will have to fall back to polling document.title
.
Note that I haven't been able to test this in all browsers, so you should test this carefully before using it.
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();
}
};
}
};
Tim Down
2010-03-23 10:36:44