Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Chrome扩展-在URL更新时加载内容脚本_Javascript_Google Chrome - Fatal编程技术网

Javascript Chrome扩展-在URL更新时加载内容脚本

Javascript Chrome扩展-在URL更新时加载内容脚本,javascript,google-chrome,Javascript,Google Chrome,我遇到了这个问题,我想在URL匹配的页面上运行内容脚本content.jshttps://www.example.com/*。我在manifest.json中定义了以下内容: { ... "content_scripts": [ { "matches": ["https://www.example.com/*"], "js": ["content.js"] } ], ... } 但是,当用户从另一个页面(比如https://www.

我遇到了这个问题,我想在URL匹配的页面上运行内容脚本
content.js
https://www.example.com/*。我在
manifest.json
中定义了以下内容:

{ 
  ...

  "content_scripts": [
    {
      "matches": ["https://www.example.com/*"],
      "js": ["content.js"]
    }
  ],

  ...
}
但是,当用户从另一个页面(比如
https://www.foo.bar
)至
https://www.example.com/*
,例如单击超链接。仅当用户直接访问
https://www.example.com/*


我正在考虑将
content.js
注入所有页面,并在后台监听
chrome.tabs.onUpdate
以查看当前URL是否匹配
https://www.example.com/*
,并根据需要将消息发送到
content.js
。有更好的解决方法吗?

您可以从后台页面以编程方式插入脚本,使发送/接收消息的函数成为executeScript的回调函数:

function processUrl(tabId, url) {
  if(url.indexOf("https://www.example.com")>-1){
    chrome.tabs.executeScript(tabId, {file:"content.js"}, function() {
      //send and receive msgs  here
    };
  }
}
然后从侦听器调用此函数。如果要使用库或其他依赖项,请首先使用库调用executeScript,然后在第一次调用的回调中使用脚本调用executeScript