我正在开发 chrome 扩展,并且我一直停留在一个非常具体的部分,backgroundjs 应该向当前事件选项卡发送消息。
这是我的 list 文件
manifest.json
{
"manifest_version": 2,
"name": "test",
"description": "Some_Test",
"version": "1.0",
"background": {
"page": "background.html"
},
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "content.js" ]
}
],
"permissions": [
"background",
"activeTab",
"tabs",
"http://*/*",
"https://*/*"
],
"browser_action": {
"default_popup": "popup.html"
}
}
popup.html
<html>
<body>
<button id="read-button">Read</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
popup.js
function readObject(e) {
console.log(chrome.extension.getBackgroundPage().read());
}
document.getElementById('read-button').addEventListener('click', readObject);
背景.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="background.js"></script>
</body>
</html>
背景.js
function read() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
return response.farewell;
});
});
}
content.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log("hello");
if (request.greeting == "hello")
sendResponse({ farewell: "goodbye" });
});
这是错误所在:
chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
return response.farewell;
});
我似乎无法访问 tabs[0]
对象,或者我无法理解它返回的数组,因为我想访问事件选项卡和 tabs[0]
只是意味着它正在获取浏览器中的第一个选项卡,而不是事件选项卡。
最佳答案
我认为只有当事件窗口是后台页面的开发人员工具时才会发生这种情况。
在测试扩展时只需切换到普通浏览器窗口或在 popup.js 中定义 read()
函数,如果不是绝对需要,则完全删除背景页面。
关于javascript - 如何将消息从backgroundjs发送到chrome扩展中的内容脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560942/