[英]Why won't my content.js script communicate with my background.js script (chrome extensions)?
I am trying to build a basic extension in google chrome which includes a content and background script.我正在尝试在 google chrome 中构建一个基本扩展,其中包括一个内容和背景脚本。 For some reason, when a new tab is created and i try to send a message from my background script to the content script, the event listener in content.js
is not receiving the message.出于某种原因,当创建一个新选项卡并且我尝试从我的后台脚本向内容脚本发送消息时, content.js
的事件侦听器未收到该消息。 I can't see any console.log
in the new tabs dev tools.我在新标签开发工具中看不到任何console.log
。 Can anyone explain where i am going wrong?谁能解释我哪里出错了?
content.js:内容.js:
//listen to background.js
/* global chrome */
chrome.runtime.onMessage.addListener(request => {
console.log("message received")
const el = document.createElement('injected');
el.id = "injected-element"
el.innerHTML = `<div> this has been injected </div>`
document.body.appendChild(el)
sendResponse({ "message":"sent from content script" });
}
);
document.addEventListener('click', () => {
this.setState({ count: this.state.count +1 });
});
background.js背景.js
chrome.runtime.onInstalled.addListener(() => {
console.log("Extension installed successfully")
});
chrome.tabs.onCreated.addListener(tab => {
chrome.tabs.sendMessage(
tab.id,
{"message":"hello from background script"}
);
});
manifest.json清单文件
{
"manifest_version": 2,
"name": "Article Scorer",
"author": "Sean Barker",
"version": "1.0.1",
"icons": {
"192": "logo192.png",
"512": "logo512.png"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": ["activeTab", "tabs", "contextMenus"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
The problem is probably because when the onCreated
listener is triggered, it attempts to send the message back to the tab, but content.js
has not been loaded yet since new tabs by default do not have a url, and your manifest declares that the content script will be injected when it matches "<all_urls>"
.问题可能是因为当onCreated
侦听器被触发时,它尝试将消息发送回选项卡,但由于默认情况下新选项卡没有 url,因此尚未加载content.js
,并且您的清单声明内容脚本将在匹配"<all_urls>"
时被注入。 content.js
is only loaded once the new tab is directed to some site. content.js
仅在新选项卡定向到某个站点后才加载。
To see this happening you can do the following:要查看这种情况,您可以执行以下操作:
onCreated
listener in background.js
.在background.js
中的onCreated
侦听器中放置一个断点。content.js
is loaded打开开发工具并查看content.js
已加载background.js
在background.js
解开并继续执行In effect, your background script is sending the message properly, but nothing is listening.实际上,您的后台脚本正在正确发送消息,但没有任何内容在侦听。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.