导航到新链接时,内容脚本无法运行

时间:2017-06-01 01:32:58

标签: javascript html google-chrome google-chrome-extension

我目前正在撰写需要在YouTube视频上投放的Google Chrome扩展程序。我有一个内容脚本,它是一个JavaScript文件,可以完成我需要它完成的所有工作。

工作正常,唯一需要注意的是,出于某种原因,每当您点击链接转到新视频时,都不会立即运行JavaScript代码;您需要重新加载页面才能使其正常工作。

的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
}

1 个答案:

答案 0 :(得分:0)

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

您可以设置一个时间间隔来检测URL changes

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

但我用这个

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

HTML5引入了一个hashchange事件,它允许您注册url哈希更改的通知,而无需使用计时器轮询它们。

window.onhashchange = function (event) {
  console.log(location.hash, event.oldURL, event.newURL);
  myfunction();
}