Detect Youtube video change with injected javascript

The idea is simple:

  • Use background.js to listen for url changes to a specific youtube tab using chrome.tabs.onUpdated
  • Once tab change is detected, send the new URL to the content-script running in that tab

The background page listens for URL changes to other tabs also but I'm pretty sure you can figure out how to fix that.

manifest.json

{
    "manifest_version": 2,
    "name": "Tab url change detection",
    "version": "1.0",
    "background": {
        "persistent":true,
        "page":"bg.html"
    },
    "content_scripts": [{
            "matches": ["http://www.youtube.com/*"],
            "js": ["app.js"]
        }
    ],
    "permissions": [
        "tabs",
        "http://www.youtube.com/*"
    ]
}

background.html

<script src="background.js"></script>

background.js

//Listen for when a Tab changes state
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    if(changeInfo && changeInfo.status == "complete"){
        console.log("Tab updated: " + tab.url);

        chrome.tabs.sendMessage(tabId, {data: tab}, function(response) {
            console.log(response);
        });

    }
});

app.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    //here we get the new 
    console.log("URL CHANGED: " + request.data.url);
});

I know it's an old thread but I hope someone else will be able to use this information.

I had a similar issue building a chrome extension for youtube. To be more specific I needed to detect the navigation within youtube.

TL;DR;
After going over most of the StackOverflow, I've ended with the following in the context.js file.

function run(){
// your youtube extention logic 
console.log('change');
}

window.onload = run;
window.addEventListener('yt-navigate-start', run,   true);

Explanation In case you wish to see all of the window events you can run getEventListeners(window).

youtube has a costume event when changing pages, the event is yt-navigate-start.

For the first time youtube loads, I used the window.onload and after that, add the event listener window.addEventListener('yt-navigate-start', run, true);

Good luck, I hope this could help.


I was recently struggling with this and I figured out what to do. I'm not sure if this is the best way to do it, but it doesn't rely on a background.js file.

var oldURL= ""

//window.setInterval takes a function and executes it after 
//a given time (defined by the second parmeter)in miliseconds

var urlChangeHandler = window.setInterval(checkUrlChange, 500)

function checkURLChange(){
  newURL = document.URL;
  if(newURL !== oldURL){
   doSomething();
   oldURL = newURL;
  }
}