我有一个根据用户输入在我的 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"....
最佳答案
我在评论中所说的有关从 popup.js
发送消息到 content.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));
}
});
关于javascript - 在 Chrome 扩展中将(对象)数组从 popup.js 传递到 content.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440888/