Chrome Extension error trying to send array from content script to popup script

Viewed 1520

I am attempting to find all of the images on the webpage the user is currently on, and display them when the user clicks on the extension. I have looked at a lot of posts and seemingly found the best way to do this: have the popup.js script message the content.js script when it is activated, and then have the content.js script get the images and send it back to the popup.js script. However, I always get an error (shown below). These are the relevant files:

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);
    }
});

I noticed that I get the following error when clicking on my extension and inspecting it:

Error in response to tabs.query: Error: Invalid value for argument 3. Property 'type': Unexpected property. at Object.callback (chrome-extension://mhnnhbbcahnfjmfgofalcmikdedelicg/popup.js:2:17) at chrome-extension://mhnnhbbcahnfjmfgofalcmikdedelicg/popup.js:1:13

I am very new to developing chrome extensions and don't really have any idea how to fix this. The error seems to suggest that the callback function is an invalid argument in chrome.tabs.query but I am not sure how. Thanks for help. Note that my background.js script is an empty file.

1 Answers
Related