Skip to content Skip to sidebar Skip to footer

Chrome Extension Content Script - Grabbing Youtube Video Titles Using Javascript

I have a simple content script for my Chrome Extension that is supposed to grab the titles of YouTube videos. My problem is that it has only worked once. I tried accessing the chil

Solution 1:

With the help of the following post, I found a solution: 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'

The first issue was my code being executed too early so the setTimeout() function solved that. The next issue was one I didn't know I would have until it was mentioned; YouTube loads it's pages dynamically so the content script only runs if the page refreshes which effectively may never happen. So mutationObserver() worked to solve that problem as suggested in the comments. One peculiar thing was that I had to observe the childlist and subtree for mutations instead of characterData even though the character data was what the thing that changed. From what I've read the old node is removed and the new one then inserted.

Here is the code:

var observer = newMutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
        if (mutation.addedNodes.length) {
            if (mutation.type == 'childList') {
                console.log(mutation.target.innerText);
            }
        }
        })
    })

functioncheckNode() {
        var targetNode = document.querySelector("h1.title.style-scope.ytd-video-primary-info-renderer");
        if (!targetNode) {
            window.setTimeout(checkNode, 500);
            return;
        }
        console.log(targetNode.innerText);
        var config = {
            childList: true,
            subtree:true
        }
        observer.observe(targetNode, config)
    }
checkNode();

Post a Comment for "Chrome Extension Content Script - Grabbing Youtube Video Titles Using Javascript"