【发布时间】: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