4

I am currently writing a Google chrome extension that needs to run on YouTube videos. I have a content script which is a JavaScript file that does all the work I need it to do.

It is working fine, the only caveat is that for some reason, whenever you click a link to go to a new video, it doesn't run the JavaScript code immediately; you need to reload the page to make it work.

manifest.json

{
"name": "Title",
"description": "description",
"version": "0.5",
"permissions": [
    "webNavigation",
    "activeTab",
    "tabs",
    "*://*.youtube.com/*"
],
"browser_action": {
      "default_icon": {                   
        "16": "image.png"         
      },
      "default_title": "name",      
      "default_popup": "popup.html"        
},

"content_scripts": [
{
  "matches": ["*://*.youtube.com/*"],
  "js": ["blocker.js"],
  "run_at": "document_end"
}
],
"manifest_version": 2
}

blocker.js

myfunction();
function myfunction(){
    //manipulate the HTML DOM
}
samsore
  • 63
  • 4
  • 1
    Possible duplicate of [Chrome extension is not loading on browser navigation at YouTube](https://stackoverflow.com/questions/18397962/chrome-extension-is-not-loading-on-browser-navigation-at-youtube) and [How to detect page navigation on Youtube and modify HTML before page is rendered?](https://stackoverflow.com/questions/34077641/how-to-detect-page-navigation-on-youtube-and-modify-html-before-page-is-rendered) – Daniel Herr Jun 01 '17 at 02:54

1 Answers1

-1
myfunction();
function myfunction(){
  //manipulate the HTML DOM
}

You can put a time interval to detect that the URL changes

var currentURL = location.href;
setInterval(function() {
     if(location.href != currentURL) {
        myfunction();
        currentURL = location.href
     }
 }, 100);

but I use this

var currentURL = location.href;
window.onclick=function(){
  if(currentURL!==location.href){
    myfunction();
    currentURL = location.href
    /*some code*/
  }
}

HTML5 introduces a hashchange event which allows you to register for notifications of url hash changes without polling for them with a timer.

window.onhashchange = function (event) {
  console.log(location.hash, event.oldURL, event.newURL);
  myfunction();
}
alessandrio
  • 4,282
  • 2
  • 29
  • 40
  • 1
    This didn't work for me. The same problem is occurring. When I navigate to a new YouTube page, the script won't run; I need to refresh the page for it to work. – samsore Jun 01 '17 at 02:16
  • I put the window.onhashchange section in my JavaScript function, but it still doesn't fix the problem. My JavaScript file doesn't get triggered at all, so it won't be able to run anything inside of that code. – samsore Jun 01 '17 at 02:26
  • the best solution is `setInterval` – alessandrio Jun 01 '17 at 02:56