Chrome扩展程序在popup.html和content.js之间的消息传递 [英] Chrome extension messaging between popup.html and content.js
问题描述
所以我有一个可以在网站上运行的脚本,它可以基于某些参数收集一些数据,这些脚本本身就可以很好地工作,但是我希望能够通过一个带有单个按钮的browserAction弹出窗口进行点击.将触发上述脚本.
我相信我的问题是我无法通过按下按钮来发送消息,我也不知道如何实现,而且我也没有阅读过浏览器操作教程./p>
这是我的代码: popup.html
<html>
<body style="width: 200px; height: 150px;">
<script src="background.js"></script>
<div id="button" style="position:absolute; left: 75px;">
<button id="mb" onclick="click()">Initialise</button>
</div>
</body>
</html>
background.js
function click() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
}
content.js
$(document).ready(function(){
init();
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.message === "clicked_browser_action"){
popup();
}
})
});
我知道我其余的代码都可以用,因为我已经通过添加
对其进行了测试browserAction.onClick.addListener(function(tab){ ... });
代替
function click() { ... }
,一切都按照我的意愿进行.
我将如何正确实现按钮?
与在html中定义事件内联相反,您需要在弹出窗口中使用Javascript添加点击事件侦听器.
document.getElementById("mb").addEventListener("click", function(e){
//event will trigger here
}
So I have this script that runs on a website and gathers some data based on certain parameters, which works perfectly fine by itself, but I want to be able to have a browserAction popup with a single button in it, which on click will trigger the aforementioned script.
I believe my problem is that I can't get the message to be sent via a press of the button, I don't know how to implement this, and no browserAction tutorial I've read tried to, either.
Here's my code: popup.html
<html>
<body style="width: 200px; height: 150px;">
<script src="background.js"></script>
<div id="button" style="position:absolute; left: 75px;">
<button id="mb" onclick="click()">Initialise</button>
</div>
</body>
</html>
background.js
function click() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
}
content.js
$(document).ready(function(){
init();
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.message === "clicked_browser_action"){
popup();
}
})
});
I know the rest of my code works, because I've tested it by adding
browserAction.onClick.addListener(function(tab){ ... });
in the place of
function click() { ... }
and everything worked exactly as I wanted it to.
How would I go about implementing the button correctly?
You need to add an on click event listener using Javascript in the popup, in contrast to defining the event inline in the html.
document.getElementById("mb").addEventListener("click", function(e){
//event will trigger here
}
这篇关于Chrome扩展程序在popup.html和content.js之间的消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!