0
JavaScript新手,決定試用Chrome擴展。我試圖將items數組傳遞給我的html文件,但它在我的Chrome擴展中的html中顯示爲未定義。這是可能做到從按鈕/彈出js文件到本地html文件?下面是我有:從popup.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();
};
};
將數據從popup.js傳遞到事件頁面,然後通過html頁面從那裏檢索數據,而不是將邏輯移動過來? – CodingNinjaInTraining
popup.js和事件頁面都位於擴展上下文中,您可以通過['chrome.runtime.getBackgroundPage'](https://developer.chrome.com/extensions/runtime#method- getBackgroundPage) –