【问题标题】:Passing array (of objects) from popup.js to content.js in chrome extension将数组(对象)从 popup.js 传递到 chrome 扩展中的 content.js
【发布时间】:2018-05-21 01:27:01
【问题描述】:

我在我的 popup.js 文件中根据用户输入创建和修改了一个数组,我希望能够通过单击按钮(在 popup.html 中)将其发送到我的 content.js 脚本。目前,chrome.runtime.sendMessage 似乎只让我将字符串(或 JSON?)类型的消息传递给 content.js,所以我很难想出一个解决方案来获取这个对象数组以及消息(一些像 'start_search') 到 content.js 执行。

这里是对象数组供参考:

var searchList = [];

这是构造它的函数(在用户提交时触发):

function addWord(userWord, userColor){ //append new word 
    var wordAndColorPair = {
        word: userWord,
        color: userColor,
        id: placementId.toString() //keep it as a string so it can be used for highlighted word's class
    }
    searchList.push(wordAndColorPair); //pushing the new object with user inputs to array
}

以下是我使用 JSON.stringify 的尝试:

popup.js:
    .
    .
    var jsonSearchList = JSON.stringify(searchList);
    chrome.tabs.sendMessage(activeTab.id, jsonSearchList);


content.js:
    alert(request.message); //alerts "undefined"....

【问题讨论】:

  • 我尝试使用 JSON.stringify 将对象数组作为字符串发送,但它不起作用,我也无法附加消息
  • JSON.stringify 的哪一部分有问题?您可以发布任何处理双方消息传递的相关代码吗?
  • JSON.stringify 是唯一的解决方案吗?
  • 消息传递 API 使用序列化 JSON 作为数据交换格式。只需使用JSON.stringify 将数据序列化为JSON 字符串,然后在另一端使用JSON.parse 将JSON 字符串反序列化。
  • 有什么方法可以传递这些信息,使用不同的方法吗? (除了 sendMessage?)

标签: javascript google-chrome google-chrome-extension sendmessage


【解决方案1】:

我在 cmets 中所说的关于从popup.jscontent.js 发送消息的示例:

Popup.html:

<body>
    <button id="test">Send data</button>
</body>
<script type="text/javascript" src="popup.js"></script>

Popup.js:

var searchList=[{test1:1},{test2:2}];
var jsonSearchList = JSON.stringify(searchList);

document.getElementById("test").addEventListener("click", function() {
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            data: jsonSearchList
        });
    });
});

Content.js:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    if (msg.data !== undefined) {
        console.log(JSON.parse(msg.data));
    }
});

【讨论】:

  • 谢谢你,因为它清除了一些东西。但是,在 request.data 上使用 JSON.parse() 之后 -> 结果是 [object Object, object Object etc..] ?
  • 发生这种情况是因为您正在记录对象的字符串表示形式,您仍然可以对其进行解析并将其存储在一个变量中,然后您可以根据需要使用该变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多