1

I'm making a simple Chrome Extension that pops out a prompt when entering certain websites. My main one would be Youtube. Here's the code that I have so far:

if(window.location.hostname ==="www.youtube.com") {
   let why = prompt("Why are you on Youtube/Watching this video?", "");   
   }; 

This works fine when entering youtube for the first time, when refreshing a page, or when going back a page using the back arrow. However, I would like it to pop up whenever I click a video, or switch pages (for example, going from the Recommended tab to the Subscriptions tab). How can I do this?

EDIT: I found code that works on this question: Detect Youtube video change with injected javascript Here's my final code:

function run(){
    if(window.location.hostname ==="www.youtube.com") {
       let why = prompt("Why are you on Youtube/Watching this video?", "");
   
       };  
}
window.onload = run;
window.addEventListener('yt-navigate-start', run,   true);

1 Answers1

1

Youtube is a Single Page Application (SPA), so the page does not reload when a video is clicked. You can read more about it here.

The code you posted is only executed when the page loads, and that happens, as you already noticed, when you first open youtube or refresh the page.

Perhaps you can try to listen to title changes, which change on each video and page, using this code snippet that I got from this thread.

    new MutationObserver(function(mutations) {
        console.log(mutations[0].target.nodeValue);
    }).observe(
        document.querySelector('title'),
        { subtree: true, characterData: true, childList: true }
    );
Raimundo
  • 53
  • 1
  • 3