Javascript 如何从后台获取要在弹出页面中显示的数据
我想在点击“获取数据”按钮时在后台显示阵列数据,但点击该按钮时什么也没做。对于chrome ext来说,这是非常新的。谢谢 manifest.json:Javascript 如何从后台获取要在弹出页面中显示的数据,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我想在点击“获取数据”按钮时在后台显示阵列数据,但点击该按钮时什么也没做。对于chrome ext来说,这是非常新的。谢谢 manifest.json: { "name":"modz", "manifest_version":2, "version":"1.0", "description":"this ext. will help you record all the urls you have visited", "background": {
{
"name":"modz",
"manifest_version":2,
"version":"1.0",
"description":"this ext. will help you record all the urls you have visited",
"background": {
"scripts": ["background.js"]
},
"browser_action":
{
"default_icon":"icon.png",
"default_popup":"popup.html"
},
"permissions":[
"tabs"
]
}
background.js:
var data=[];
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var url = tab.url;
if (url!=="undefined" && changeInfo.status=="complete")
{
data.push (tab.url);
alert(data.length);
}
}
);
chrome.runtime.onMessage.addListener(function(message,sender,sendrespose){
//send the array data back
});
popup.js:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('btn').addEventListener('click',function(){
chrome.runtime.sendMessage("getdata");
});
});
popup.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="C:\Users\modz\Desktop\modz_extention\popup.js"></script>
<style type="text/css">
body{
width:440px;
}
</style>
</head>
<body>
<input id="btn" type="button" value="get data" />
<div id="data"></div>
</body>
</html>
身体{
宽度:440px;
}
消息传递的官方参考是。在您的情况下,您希望background.js
具有
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
sendResponse({"dataArray":data});
});
popup.js
将
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('btn').addEventListener('click',function(){
chrome.runtime.sendMessage({},function(response){
document.getElementById("data").textContent = response.dataArray.toString();
});
});
});
这也适用于内容脚本。但是,如果内容脚本在默认的document\u end
下运行,它就不需要DOMContentLoaded
事件,因为document\u end
随后发生
这实际上是在发送一条空消息(空对象{}
)。如果您想发送不同的消息,您会想更改它。这也是为什么message
没有在background.js
中使用的原因
因为你并不是真的在发送信息,另一种方法是使用background.js
不需要侦听器,popup.js
将具有:
chrome.runtime.getBackgroundPage(function(backgroundWindow){
document.getElementById("data").textContent = backgroundWindow.data.toString();
});
还有两件事:
无法使用popup.html
的绝对路径。将两者都放在扩展目录中,并使用相对路径:popup.js
src=“popup.js”
- 谷歌建议您将背景页面转换为。最大的区别是,事件页面中不能有全局变量
(可以,但在重新加载事件页面时会重置)。如果你在这方面有困难,我建议你把你的扩展作为背景页面,然后再发布另一个问题data
sendrespose(data)
。你能给我一个代码片段吗?因为我对chrome ext非常陌生,还有按钮是否可以使用。你能帮我一下吗?谢谢你,我会推荐你,或者。请把你以前的评论作为答案发布,因为这是我的答案,所以我可以接受