In Javascript, is there a technique to listen for changes to the title element?
5 years later we finally have a better solution. Use MutationObserver!
In short:
new MutationObserver(function(mutations) {
console.log(mutations[0].target.nodeValue);
}).observe(
document.querySelector('title'),
{ subtree: true, characterData: true, childList: true }
);
With comments:
// 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, childList: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
Looks awesome, but it doesn't work when I set document.title directly:
document.title = 'test';
As a workaround, you can add:
document.__defineSetter__('title', function(val) { document.querySelector('title').childNodes[0].nodeValue = val; });
. Which probably doesn't work in all browsers, unfortunately.It wasn't working for me when I set
document.title
directly either. (I used Chrome 52.) However, addingchildList: true
to the config object fixed it.new MutationObserver(function() {console.log(document.title);}).observe(document.querySelector('title'),{ childList: true });
it works