In Javascript, is there a technique to listen for changes to the title element?
Advertisement
Answer
5 years later we finally have a better solution. Use MutationObserver!
In short:
JavaScript
x
7
1
new MutationObserver(function(mutations) {
2
console.log(mutations[0].target.nodeValue);
3
}).observe(
4
document.querySelector('title'),
5
{ subtree: true, characterData: true, childList: true }
6
);
7
With comments:
JavaScript
1
15
15
1
// select the target node
2
var target = document.querySelector('title');
3
4
// create an observer instance
5
var observer = new MutationObserver(function(mutations) {
6
// We need only first event and only new value of the title
7
console.log(mutations[0].target.nodeValue);
8
});
9
10
// configuration of the observer:
11
var config = { subtree: true, characterData: true, childList: true };
12
13
// pass in the target node, as well as the observer options
14
observer.observe(target, config);
15