我想在单击“获取数据”按钮时显示后台的数组数据,但当我单击该按钮时什么也没做,这对于 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": {
"scripts": ["background.js"]
},
"browser_action":
{
"default_icon":"icon.png",
"default_popup":"popup.html"
},
"permissions":[
"tabs"
]
}
背景.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>
最佳答案
消息传递的官方引用是 here 。在您的情况下,您希望 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_end
处运行,则不需要 DOMContentLoaded
事件,因为 document_end
会在之后发生。
这实际上是发送一条空消息(空对象{}
)。如果您想发送不同的消息,您会想要更改它。这也是 background.js
中不使用 message
的原因。
由于您并未真正发送消息,因此另一种方法是使用 getBackgroundPage
。 background.js
不需要监听器,而 popup.js
则需要:
chrome.runtime.getBackgroundPage(function(backgroundWindow){
document.getElementById("data").textContent = backgroundWindow.data.toString();
});
还有两件事:
popup.html
不能使用popup.js
的绝对路径。将两者都放在扩展目录中,并使用相对路径:src="popup.js"
。Google 建议您将后台页面转换为 event pages 。最大的区别是你不能在事件页面中使用全局变量
data
(可以,但当事件页面重新加载时它会被重置)。如果您无法正常工作,我建议您将扩展程序作为后台页面工作,然后发布另一个问题。
关于javascript - 如何从后台获取数据并显示在弹出页面中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31357549/