我想从reddit获取所有标题,并将其传递给 backgroundScript.js 。
它会显示页面控制台中的所有网址,但出于某种原因,它会在背景页面上显示此消息:
我的代码:
的manifest.json :
{
"manifest_version": 2,
"name": "Testing stuff",
"description": "This extension is for testing purposes",
"version": "1.0",
"background": {
"scripts": [ "backgroundScript.js" ]
},
"content_scripts": [ {
"exclude_matches": [ "*://*.reddit.com/r/*/ comments /*" ],
"js": [ "contentScript.js" ],
"matches": [ "*://*.reddit.com/r/*", "*://*.reddit.com/", "*://*.reddit.com/me/m/*", "*://*.reddit.com/user/*/ m /*" ],
"run_at": "document_end"
} ],
"permissions": [ "history", "tabs", "http://*/ *" ]
}
contentScript.js :
titleUrls = document.querySelectorAll("a.title");
for (i = 0; i < titleUrlsArray.length; i++) {
var u = i + 1
console.log(u + " " + titleUrls[i].href);
}
chrome.runtime.sendMessage(titleUrls)
backgroundScript.js :
chrome.runtime.onMessage.addListener(
function (response, sender, sendResponse) {
var data = response;
alert("in backgroundScript.js, received " + data[1].href);
}
);
为什么在主页的控制台中显示所有网址时,它会在后台页面上显示undefined
?我做错了什么?
答案 0 :(得分:2)
runtime.sendMessage()
消息中发送DOM元素 runtime.sendMessage()
中的消息必须是“JSON-ifiable对象”。 DOM元素/节点不是JSON-ifiable。因此,你不能发送它们。
您需要做的而不是尝试序列化DOM元素最终取决于您在后台脚本中需要此信息的原因。
您已声明所需信息是.href
媒体资源中的网址。您可以构建这些URL的数组并发送:
contentScript.js :
titleUrls = document.querySelectorAll("a.title");
var urlList=[];
for (i = 0; i < titleUrlsArray.length; i++) {
var u = i + 1
console.log(u + " " + titleUrls[i].href);
urlList.push(titleUrls[i].href);
}
chrome.runtime.sendMessage(urlList);
backgroundScript.js :
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
var urlList = response;
alert("in backgroundScript.js, received " + urlList[0]);
});