2017-08-07 25 views
0

我已經制作了一個Chrome擴展程序,可以在單擊瀏覽器操作按鈕時打開Windows計算器。現在,我試圖通過使用JavaScript代碼單擊來啓動網頁上的擴展。如何從網頁與擴展程序的後臺腳本進行通信

<!doctype html> 
 
<html> 
 
    <head><title>activity</title></head> 
 
<body> 
 
    <button id="clickactivity" onclick="startextension()">click</button> 
 
    <script> 
 
\t 
 
\t function startextension(){ 
 
\t \t //run/start the extension 
 
\t } 
 
\t 
 
\t </script> 
 
</body> 
 
</html>

這是我background.js代碼:

chrome.browserAction.onClicked.addListener(function(){ 
    chrome.extension.connectNative('com.rivhit.calc_test'); 
}); 

有沒有辦法做到這一點?

回答

0

這是通過消息傳遞完成的。所以,你的網頁可以發送一條消息:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) { 
console.log(response.farewell); 
}); 

和你的分機可以聽吧:

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) { 
    console.log(sender.tab ? 
      "from a content script:" + sender.tab.url : 
      "from the extension"); 
if (request.greeting == "hello") 
    sendResponse({farewell: "goodbye"}); 
}); 

來源:https://developer.chrome.com/extensions/messaging

相關問題