Javascript Chrome扩展-在URL更新时加载内容脚本
我遇到了这个问题,我想在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.
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