尝试将数组从内容脚本发送到弹出脚本时出现 Chrome 扩展程序时出错
Chrome Extension error trying to send array from content script to popup script
我正在尝试查找用户当前所在的网页上的所有图像,并在用户单击扩展程序时显示它们。我看了很多帖子,似乎找到了最好的方法:让弹出窗口.js脚本发送内容消息.js脚本何时激活,然后让内容.js脚本获取图像并将其发送回弹出窗口.js脚本。但是,我总是收到错误(如下所示)。这些是相关文件:
manifest.json
{
"manifest_version": 2,
"name": "Picture Finder",
"version": "1.0",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs"
]
}
弹出窗口.html
<!DOCTYPE html>
<html>
<head>
<title>Picture Finder</title>
<script src="popup.js"></script>
</head>
<body>
<h1><center>Picture Finder</center></h1>
<img id="pic" src="" height="400" width="400">
</body>
</html>
弹出窗口.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.runtime.sendMessage(tabs[0].id, {type: "getContent"},
function(response) {
console.log(response); //this never gets logged
document.getElementById('pic').src = response[0].src;
});
});
内容.js
var picArray = document.getElementsByTagName("img");
var srcArray = [];
for(var i = 0; i < picArray.length; i++){
srcArray.push(picArray[i].src);
}
//console.log(picArray); //this gets logged correctly
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
switch(message.type){
case "getContent":
console.log(srcArray);//this never gets logged
sendResponse(srcArray);
break;
default:
console.error("unexpected message: ", message);
}
});
我注意到在单击扩展并检查它时出现以下错误:
响应 tabs.query 时出错:错误:参数 3 的值无效。属性"类型":意外属性。 at Object.callback (chrome-extension://mhnnhbbcahnfjmfgofalcmikdedelicg/popup.js:2:17) 在铬 extension://mhnnhbbcahnfjmfgofalcmikdedelicg/popup.js:1:13
我对开发chrome扩展程序非常陌生,真的不知道如何解决这个问题。该错误似乎表明回调函数是chrome.tabs.query中的无效参数,但我不确定如何。感谢您的帮助。请注意,我的背景.js脚本是一个空文件。
您尝试执行的操作都不起作用,因为您无法通过消息传递传递 DOM 节点(它不可 JSON 序列化)。
你应该只传递你关心的属性,例如,如果你需要src
的 - 提取它们的数组并传递该数组。
更新:啊,我现在看到了错误的原因。您正在使用chrome.runtime.sendMessage
而在这种情况下,您应该使用chrome.tabs.sendMessage
- 它在无效调用时阻塞(第一个参数,如果存在,应该是一个字符串 - 您尝试传递一个数字,因此它被解释为消息,然后对象混淆它)。
要修复,只需将chrome.runtime.sendMessage
替换为 chrome.tabs.sendMessage
.
- chrome扩展:尽管运行了at:documentidle,js脚本还是过早启动
- java脚本在Chrome和其他浏览器中对LocaleTimeString的不同行为
- 如何让JS脚本在导航后继续运行(谷歌chrome控制台)
- 是否可以通过Chrome扩展内容脚本打开Chrome外部协议请求
- 在chrome web商店中打开时,是否有允许执行内容/后台脚本的解决方案
- Google Chrome扩展程序可以检测所有脚本何时加载完成吗
- 加载Chrome扩展中的脚本错误
- chrome扩展-内容脚本随需应变
- Chrome存储API无法使用内容脚本
- Chrome内容脚本制作cookie;chrome重新启动时,cookie会被删除.如何使其稳定
- Chrome扩展:加载窗口后执行脚本
- 如何动态添加或删除Chrome扩展、内容脚本、javascript文件
- 内容安全策略指令:;脚本src'self'blob:文件系统:chrome扩展资源:“;获取是否时
- Chrome审核:在外部CSS文件之间的头中发现了1个内联脚本块&”;
- 为内容脚本[Chrome扩展]获取本地存储价值的简单方法
- 拒绝加载脚本Chrome扩展
- InnerText在内容脚本Chrome扩展中返回未定义的内容
- 未在内容脚本Chrome扩展上触发事件
- 选项启用了内容脚本Chrome扩展,没有背景页
- 动态加载内容脚本(chrome扩展)