javascript - 将对象从 popup.js 发送到本地 html 页面

标签 javascript google-chrome-extension

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();
    };
};

最佳答案

  1. document.querySelector('button') 不会得到任何结果,使用 document.querySelector('p')document.querySelector('#target' )
  2. 创建hello.html时,popup.html已经关闭,所以当你调用chrome.runtime.sendMessage发送消息时,事实上这个消息 channel 的另一端根本没有打开。这就是为什么你在回调中得到 undefined 的原因,你可以尝试移动这个 message passing逻辑从 popup.jsEvent page或使用类似 chrome.storage 的内容相反。

关于javascript - 将对象从 popup.js 发送到本地 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38649766/

相关文章:

javascript - 如何使用 Kendo UI 在多选中获取更改的元素?

javascript - for 循环创建 Image(),但获取宽度和高度失败

ssl - 如何获取 'Chrome has detected insecure content' 而不是 'Chrome has detected either high-risk insecure content'

javascript - Jquery 更新下面的 CSS

javascript - 在JavaScript中将视频播放速率属性从1设置为2,从1设置为0.5时,究竟发生了什么变化?

Javascript - 动态改变绝对定位

javascript - 解决我的 chrome 扩展中的 eval()

google-chrome - 如何调试 page_action chrome 扩展

javascript - 将信息从网站传递到 chrome 扩展程序

google-chrome - "Extension Install Failure: Package is invalid. Details: ' 'page_action.default_icon' 的值无效。 '"