JavaScript 新手,决定尝试 Chrome 扩展。我试图将 items 数组传递到我的 html 文件中,但它在我的 chrome 扩展的 html 中显示为未定义。是否可以从按钮/弹出 js 文件到本地 html 文件执行此操作?这是我所拥有的:
Manifest.json
{
"manifest_version": 2,
"name": "Testing",
"short_name": "Testing",
"version": "1",
"browser_action": {
"default_popup": "./button.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
}
Popup.js
var items = {};
var type = ["1","2","3"];
type.forEach(function(type,index){
//code to store stuff into items array
}
console.dir(items) //shows everything was stored correctly
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request.action == "getData") {
sendResponse(items);
}
return true;
});
chrome.tabs.create({url: './hello.html', selected:true});
hello.html
<!doctype html>
<html lang="en">
<head>
<script src="./pasteData.js"></script>
</head>
<body>
<p id="target">PARAGRAPH</p>
</body>
</html>
pasteData.js
function getData() {
chrome.runtime.sendMessage({"action": "getData"}, function(data) {
document.getElementById("target").innerHTML = data;
});
};
window.onload = function() {
document.querySelector('button').onclick = function(e) {
e.preventDefault();
getData();
};
};
最佳答案
document.querySelector('button')
不会得到任何结果,使用document.querySelector('p')
或document.querySelector('#target' )
- 创建
hello.html
时,popup.html
已经关闭,所以当你调用chrome.runtime.sendMessage
发送消息时,事实上这个消息 channel 的另一端根本没有打开。这就是为什么你在回调中得到undefined
的原因,你可以尝试移动这个 message passing逻辑从popup.js
到 Event page或使用类似chrome.storage
的内容相反。
关于javascript - 将对象从 popup.js 发送到本地 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38649766/