2015-11-06 122 views
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; 
     }); 

enter image description here

看來,我無法訪問tabs[0]對象或我無法理解它返回數組,因爲我想訪問活動標籤和tabs[0]僅僅意味着它獲取瀏覽器中的第一個選項卡,而不是活動選項卡。

回答

1

我認爲這隻有在活動窗口是背景頁面的開發工具時纔會發生。

只需在測試擴展名時切換到正常瀏覽器窗口,或在popup.js中定義read()函數,並在完全不需要的情況下完全刪除背景頁面。

相關問題