0
我正在處理chrome擴展,並且我堅持在backgroundjs假設發送消息到當前活動選項卡的非常特定的部分。如何將郵件從backgroundjs發送到Chrome擴展中的內容腳本?
這是我的清單文件
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]
僅僅意味着它獲取瀏覽器中的第一個選項卡,而不是活動選項卡。