2017-08-07 85 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

相关问题