我一直在努力让popup.js使用chrome api sendMessage
和onMessage
与我的Chrome扩展程序的其余部分进行对话。出于测试目的,我现在想要的是在popup.js上按下按钮时将某些内容记录到当前活动的选项卡上。这看起来应该很简单,但我无法弄清楚问题是什么。非常感谢任何帮助和解释!
popup.html
<!DOCTYPE html>
<body>
<p>testing</p>
<input type="submit" id="clickme" value="button">
</body>
popup.js
function popup(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("clickme").addEventListener("click",popup)
});
content.js(我希望这会将'启动'记录到我的活动标签的控制台上)
// content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
console.log('started')
}
}
);
以防它适用,这是manifest.json
{
"manifest_version":2,
"name": "extension",
"version": "0.1",
"content_scripts":[
{
"matches": [
"<all_urls>"
],
"js":["jquery-3.1.1.min.js","content.js"]
}],
"browser_action":{
"default_icon":"icon.png",
"default_popup":"popup.html"
},
"background":{
"scripts":["background.js"]
}
}