YouTube Reaction Overview 3
const API_KEY = "YourYtApiKey"; | |
const BASE_URL = "https://www.googleapis.com/youtube/v3/videos?part=statistics&key=" + API_KEY + "&id="; | |
const ID_STATS_MAP = {}; | |
const UNIQUE_IDS = new Set(); | |
(function() { | |
window.addEventListener("load", function(event) { | |
addRootObserver(); | |
getCurrentElementAndEvalData(); | |
}); | |
})(); |
function addRootObserver() { | |
const root = document.querySelector("#content #page-manager"); | |
if(!root) { | |
window.setTimeout(addRootObserver, 500); | |
return; | |
} | |
// At the moment of the first page visit either just one <ytd-browse> element or one <ytd-search> element exists | |
const elementsToObserve = root.querySelectorAll("ytd-browse, ytd-search"); | |
elementsToObserve.forEach( (element) => { | |
addSubObserver(element); | |
}); | |
// if the user switches to a section he has not visited before a new node will be added. Also observe this node | |
const observerOptions = {childList: true}; | |
const observer = new MutationObserver(function(mutationList, observer) { | |
mutationList.forEach( (mutation) => { | |
if (!mutation.addedNodes) { | |
return | |
} | |
for (let i = 0; i < mutation.addedNodes.length; i++) { | |
const node = mutation.addedNodes[i]; | |
const tagName = node.tagName.toLowerCase(); | |
if(tagName === "ytd-search" || tagName === "ytd-browse") { | |
addSubObserver(node); | |
} | |
} | |
}); | |
}); | |
observer.observe(root, observerOptions); | |
} |
function addSubObserver(node) { | |
const observerOptions = {attributes: true, attributeFilter: ["role"], childList: true, subtree: true}; | |
const observer = new MutationObserver(function(mutationList, observer) { | |
mutationList.forEach( (mutation) => { | |
if(mutation.type === "attributes" && mutation.target.getAttribute("role") === "main") { | |
const current_elements = getVideoAnchorElements(mutation.target); | |
getIdsAndQueryData(current_elements); | |
} | |
if(mutation.type === "childList" && mutation.addedNodes && mutation.addedNodes.length > 0) { | |
let addedElements = new Set(); | |
mutation.addedNodes.forEach( (addedNode) => { | |
if(addedNode.tagName) { | |
const tagName = addedNode.tagName.toLowerCase(); | |
if(tagName === "ytd-video-renderer" || | |
tagName === "ytd-rich-item-renderer" || | |
tagName === "ytd-grid-video-renderer") { | |
const linkElement = addedNode.querySelectorAll("a")[1]; | |
const id = getVideoIdFromUrl(linkElement.href); | |
if(!UNIQUE_IDS.has(id)) { | |
UNIQUE_IDS.add(id); | |
addedElements.add(linkElement); | |
} | |
} | |
} | |
}); | |
if(addedElements.size > 0) { | |
getIdsAndQueryData(Array.from(addedElements)); | |
} | |
} | |
}); | |
}); | |
observer.observe(node, observerOptions); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment