1

I'm trying to write a chrome extension that executes some code when the user is on a youtube page with a video. As far as I can tell, my code is correct, but It isn't working.

eventPage.js:

chrome.webNavigation.onCompleted.addListener(function(){
  console.log("Test")
},{url: [{pathContains: "watch", hostSuffix: "youtube.com"}]});

and my manifest file

{
  "manifest_version": 2,

  "name": "youtubeExtension",
  "description": "A chrome extension for youtube",
  "version": "0.1",

  "permissions": ["https://www.youtube.com/", "webNavigation"],
  "background": {
    "scripts": ["eventPage.js"],
    "persistant": false
  }
}

It seems onCompleted doesn't work on youtube.

King_llama
  • 195
  • 2
  • 12
  • What exactly is the problem? The event is not fired when you navigate from one video to another? – Xan Dec 02 '14 at 14:11

2 Answers2

8

Instead of using webNavigation you can also use

Add this to your background.js

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {
    if (tab.url.indexOf("youtube.com") != -1) {
      alert("Youtube load complete");
      injectScripts();
    }

  }
});

and add the following to your mainfest.json

"permissions": ["https://www.youtube.com/", "webNavigation","tabs"]

This will work just as well

  • Welcome to SO. You should be aware that stack snippets are really only for self contained html/css/js. An extension is javascript, but it can't really run in a snippet, so it doesn't quite make sense to post it that way. – Teepeemm Dec 02 '14 at 13:23
  • if you open youtube as background tab it will fire too. TS means the currently visible tab. – Evgeniy Mar 17 '20 at 17:05
  • Thank you for this answer. It was exactly what i was looking for. @Jamshed Katta. – John Yepthomi Jul 18 '21 at 19:03
7

chrome.webNavigation.onCompleted is only triggered when a document has finished loading. When you navigate to a different page on YouTube, the new page is not really "loaded" in a traditional way, but the page is dynamically updated, and the URL is replaced using history.pushState. To detect this kind of "navigations", use the chrome.webNavigation.onHistoryStateUpdated event in addition to the onCompleted event.

Another way to detect videos on YouTube pages is by using content scripts on YouTube and some event specific to YouTube, see this answer.

Rob W
  • 328,606
  • 78
  • 779
  • 666