【发布时间】:2015-11-06 06:42:12
【问题描述】:
我正在开发 chrome 扩展,我一直坚持一个非常具体的部分,假设 backgroundjs 会向当前活动选项卡发送消息。
这是我的清单文件
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);
background.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="background.js"></script>
</body>
</html>
background.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] 只是意味着它正在获取浏览器中的第一个选项卡而不是活动选项卡。
【问题讨论】:
标签: javascript google-chrome google-chrome-extension