I have the following code injected into a page on document start. It's supposed to listen for video elements and changes to the video element's src attribute.
var observer;
function logStuff(node) {
console.log(node.src);
}
function checkAllVideos() {
document.querySelectorAll('video').forEach(function (node) {
logStuff(node);
node.onloadedmetadata = function() {
logStuff(node);
}
});
}
function addObserver() {
function checkNode(node) {
if (node.constructor.name == "HTMLVideoElement") {
logStuff(node);
node.onloadedmetadata = function() {
logStuff(node);
}
}
}
observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
mutation.addedNodes.forEach(function (node) {
checkNode(node);
});
});
});
observer.observe(document, {subtree: true, childList: true, characterData: true});
}
addObserver();
checkAllVideos();
The polling version of the above is:
window.setInterval(function(){
checkAllVideos();
}, 1000);
For some weird reason, when injected into https://dailymotion.com, the mutation observer never works but the polling code works..
If I inject the mutation observer code into youtube's web-page, it works fine.. Both versions of the code works on youtube but only the polling setInterval code works on dailymotion. Any ideas why?
I just want to be notified when any HTMLVideoElement (<video>) changes its src attribute.
Why does the mutation observer not work?
The web-page adds the video tag via: <link rel="alternate" href="https://www.dailymotion.com/services/oembed?url=https%3A%2F%2Fwww.dailymotion.com%2Fvideo%2Fx7ojouk" type="application/json+oembed" title="Surgeon Explains How to Tie Surgical Knots" data-rh="true">
and that href contains an iFrame.
Instead of observing entire document. I have created an observer for each video element and it seems to work.