【发布时间】:2016-07-09 02:03:31
【问题描述】:
我正在尝试查找用户当前所在网页上的所有图像,并在用户单击扩展程序时显示它们。我查看了很多帖子,似乎找到了最好的方法:让 popup.js 脚本在激活 content.js 脚本时向它发送消息,然后让 content.js 脚本获取图像并将其发回到 popup.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"
]
}
popup.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>
popup.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;
});
});
content.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 的值无效。属性“类型”:意外属性。 在 Object.callback (chrome-extension://mhnnhbbcahnfjmfgofalcmikdedelicg/popup.js:2:17) 在 chrome-extension://mhnnhbbcahnfjmfgofalcmikdedelicg/popup.js:1:13
我对开发 chrome 扩展非常陌生,我真的不知道如何解决这个问题。该错误似乎表明回调函数是 chrome.tabs.query 中的无效参数,但我不确定如何。感谢帮助。 请注意,我的 background.js 脚本是一个空文件。
【问题讨论】:
-
在这个
chrome.runtime.sendMessage(tabs[0].id, {type: "getContent"},为什么你要传递标签ID?如果需要,您应该将其传递为chrome.runtime.sendMessage({id: tabs[0].id, type: "getContent"}, function() {})。 -
@RafiqueMohammed 它贴在上面!我只有一个功能
-
@Apb False,调用正确。
-
@Apb 好的,谢谢,我将其更改为您建议的方式,现在出现新错误:>TypeError: Cannot read property '0' of undefined
标签: javascript google-chrome-extension callback