I wrote a content script to run inside YouTube:
let id = '';
while (true) {
let newId = await getVideoId(true);
if (newId && newId !== id) {
console.log('New id', newId);
await handleVideo();
id = newId;
}
await pause(50);
}
Whenever the user visits another video, handleVideo
interacts with the DOM elements. Internally, handleVideo
uses myQuerySelector
that follows to get an element as soon as it is available:
function pause(delay) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
// Wait for at most maxDelay time
async function myQuerySelector(selector, all = false, maxDelay = 10000) {
const delay = 50; //ms
let totalDelay = 0;
let elements = [];
while (totalDelay <= maxDelay) {
elements = Array.from(document.querySelectorAll(selector))
if (elements.length) break;
await pause(delay);
totalDelay += delay;
}
console.log(`Found after ${totalDelay}`, selector)
return all ? elements : elements[0];
}
The difficulty I am facing is that when I visit a new video, the elements are available right away, but the content I am getting from those elements is the content from the previous video. How do I make sure that the elements have been updated?
P.S. The strangest thing is that this happens even when the user visits the channel page between the two videos. How do the elements persist in this case?