我正在尝试将新的选项卡URL从background.js发送到content.js。.sendMessage((执行但未到达content.js
background.js:
chrome.tabs.onUpdated.addListener(
function (tabId, changeInfo, tab) {
if (changeInfo.url) {
chrome.tabs.sendMessage(tabId, {
url: changeInfo.url
})
}
}
);
content.js:
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
console.log('here');
});
manifest.json:
{
"manifest_version": 2,
"name": "Url tracker",
"description": "Track your latest visited URLs",
"version": "0.0.1",
"icons": {
"16": "logo-small.png",
"48": "logo-small.png",
"128": "logo-small.png"
},
"permissions": [
"activeTab",
"tabs"
],
"background": {
"scripts":["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["<all_urls>"],
"all_frames": true,
"js": ["content.js"]
}]
}
-
默认情况下,内容脚本在DOMContentLoaded之后运行(可以更改(,但当选项卡开始加载时,即在内容脚本运行之前,URL会报告给onUpdated。
解决方案是添加一个检查以跳过第一次更新,因为这是不需要的:内容脚本的一个实例在每个匹配的网页中运行,并且它已经知道其页面的
location.href
。if (changeInfo.url && tab.status === 'complete') {
-
在上重新加载扩展后chrome://extensions页面(或从网络商店更新它(,它的所有内容脚本都得到";"孤儿化";无法接收消息。
解决方案是显式地重新注入它们。