-1

I have been working on creating my first chrome extension. I have done several of the sample extensions that can be found at https://developer.chrome.com/extensions/getstarted

How do I make an extension that will return a list of the urls of all of the images on an open tab in chrome? I have already asked this, but I have updated my question to hopefully make it more clear.

I know the basics in javascript, so I would like to create the extension with that language. This is not like the other in that I would like to get the full url and I would like to use simple javascript instead of trying to use json which I don't know.

Here is my manifest.json file

{
"name": "Getting Started",
"description": "Get The sources of the images",
"version": "2.0",
"permissions":[
    "activeTab",
    "tabs"
],
"browser_action":{
    "default_title": "Image Source",
    "default_popup": "popup.html"
},
"content_scripts":[
    {
        "matches": ["<all_urls>"],
        "js": ["content.js"]
    }
],
"manifest_version": 2 
}

And here is my content.js file

var len = document.images.length;
var imgs = document.images;
var sources = "";
for (var i = 0; i < imgs.length; i++){
     sources = sources + imgs[i].src + "<br>";
}
document.getElementById("sources").innerHTML = sources;
/*if (len > 0){
    alert(len + " images were found on page");
}
else{
    alert("No images were found on page");
}*/ // Used these to see if there were any images on the page

And finally my popup.html

<html>
<head>
    <title>Awesome extension</title>
    <script src="content.js"></script>
</head>
<body>
    <p id="sources">There might be images here</p>    
</body>
</html>
  • I would suggest that you read the [Chrome extension architecture overview](https://developer.chrome.com/extensions/overview#arch) (and perhaps work through reading the pages linked from there). It has overall architecture information which should help your understanding of how things are generally organized/done. – Makyen Dec 30 '16 at 20:27

1 Answers1

5

You can use Array.prototype.map:

var imageUrls = Array.prototype.map.call(document.images, function (i) {
    return i.src;
});

That should give you an array of all the image urls.

Edit:

So to get the images from the active tab when your extension is clicked you can inject your content script using chrome.tabs.executeScript instead of having a content_scripts entry in the manifest.json and use the Array.prototype.map function to get an array of the images' sources:

popup.html

<html>
    <head>
        <title>Awesome extension</title>
        <script src="popup.js"></script>
    </head>
    <body>
        <p id="sources">There might be images here</p>    
    </body>
</html>

popup.js

var callback = function (results) {
    // ToDo: Do something with the image urls (found in results[0])

    document.body.innerHTML = '';
    for (var i in results[0]) {
        var img = document.createElement('img');
        img.src = results[0][i];

        document.body.appendChild(img);
    }
};

chrome.tabs.query({ // Get active tab
    active: true,
    currentWindow: true
}, function (tabs) {
    chrome.tabs.executeScript(tabs[0].id, {
        code: 'Array.prototype.map.call(document.images, function (i) { return i.src; });'
    }, callback);
});

manifest.json

{
    "name": "Getting Started",
    "description": "Get The sources of the images",
    "version": "2.0",
    "permissions":[
        "activeTab",
        "tabs"
    ],
    "browser_action":{
        "default_title": "Image Source",
        "default_popup": "popup.html"
    },
    "manifest_version": 2 
}
Hyddan
  • 1,297
  • 15
  • 24
  • Great. That helps me get the list of urls, but how do I view them with my popup.html. What I have tried so far always says that there are no images because it runs content.js on my popup.html page. – Christopher Benner Dec 30 '16 at 17:39
  • I understood from the HTML in your popup that the images would be in there? If you want to access the current tab have a look at this for example: http://stackoverflow.com/questions/1964225/accessing-current-tab-dom-object-from-popup-html – Hyddan Dec 30 '16 at 17:43
  • Why the downvote? – Hyddan Dec 30 '16 at 23:53
  • I didn't downvote you. Someone else must have. – Christopher Benner Dec 30 '16 at 23:55
  • @Hyddan, I down-voted. I did so because what you have provided answers only a limited part of the question. The question is asking how to, from within a Chrome extension popup, get a list of the image URLs from an open tab. Your answer provides one method of obtaining an array of image URLs from code that is running in either the page context, or the content script context. Doing that is only part of what is needed. You appear to have come at this from the point of view of standard JavaScript without considering the larger problem space of being in a Chrome extension popup. – Makyen Dec 31 '16 at 00:23
  • @Makyen, fair enough & lesson learned. As per my earlier comment I first interpreted it as if the images would be in the popup.html but for next time I will first ask if that is in fact the case before posting an answer. – Hyddan Dec 31 '16 at 00:37
  • @Hyddan, I think we all have done something similar (misinterpret the question, and/or answer too quickly). That does not mean you could not improve your answer to fully answer the question. If you do, ping me and I will revisit if I feel a down-vote, or up-vote, is appropriate. I do try to come back to questions & answers which I down-vote after they are edited to see if they have been improved such that changing my vote is appropriate (e.g. I have done so on the dup-target for this question after code was added to it). (cont') – Makyen Dec 31 '16 at 00:56
  • @Hyddan, (cont') This situation is complicated by this Question being a dup of Op's another one. However, you could still improve this answer and then move it to the original question. I've moved an answer to the dup-target more than once after realizing I've answered a question which is more appropriate to close as a duplicate. Obviously, generally doing so depends on the answer being more generically relevant (not an issue here do to the direct nature of the duplicate). If you do improve & move it, please ping me prior to deleting it here so I can revisit my vote prior to the deletion here. – Makyen Dec 31 '16 at 00:58
  • @Makyen, So I updated the answer with a section on how to get data from the page to the popup, but I am not sure how I would move it to the other question. Perhaps it is because I have to little reputation but I cannot post an answer to a closed question. – Hyddan Dec 31 '16 at 12:47
  • @Hyddan, You can't actually "move" an answer from one question to another. What I have done in the past is add it as an answer (copy&paste) on the duplicate target, then delete it from the closed question. You will not be able to add it to the other question until it gets opened. – Makyen Dec 31 '16 at 17:20
  • @Hyddan, BTW: What you have will not work. The default [Content Security Policy](https://developer.chrome.com/extensions/contentSecurityPolicy) will [prevent any scripts within ` – Makyen Dec 31 '16 at 17:23
  • @Hyddan, I would also suggest injecting the content script using `chrome.tabs.executeScript()` rather than a `content_scripts` entry in *manifest.json*. Injecting into `` just to wait for a message from the background script is wasteful of resources. While it is not that bad for such a small script, it is a pattern that should be discouraged. It also allows using the return value from the script to send the information back instead of `runtime.sendmessage()` & `runtime.onMessage` ([example](http://stackoverflow.com/a/39319198/3773011)). You might also want to use `document.images`. – Makyen Dec 31 '16 at 17:36
  • @Hyddan, OK, the other Question is open. Prior to moving this answer, I would suggest editing it here and getting me to remove the downvote. For me to remove my downvote please move the code you currently have in ``. Doing that will make it possible that the code would work. Without that change, the popup will just generate a Content Security Policy error. With just that change I will remove my downvote. Implementing the rest of the suggestions would get an upvote from me. – Makyen Jan 03 '17 at 05:12
  • @Makyen, you're right, executeScript is less wasteful, changed to that instead. – Hyddan Jan 03 '17 at 13:00
  • @Hyddan. Thanks. I've upvoted. If you do move it (copy&paste, then delete here), please tell me and I will be sure to upvote it on the other question. – Makyen Jan 03 '17 at 16:18
  • @Makyen, moved it to the other question, but it seems I can't delete this since it's accepted. – Hyddan Jan 04 '17 at 12:20
  • @Hyddan, OK. Thanks for telling me. I've upvoted over there. One suggestion: As opposed to saying "you can skip the content script..", I would suggest something like "instead of using a `content_scripts` entry in your *manifest.json*, you can inject your content script using `chrome.tabs.executeScript()`". As it is currently worded, it could confuse someone into thinking that they don't need to use a content script at all, when the reality is that `chrome.tabs.executeScript()` is just an alternate way to inject a content script. – Makyen Jan 04 '17 at 12:27
  • Fair point, will do – Hyddan Jan 04 '17 at 12:29
  • what about images inside css ? – pery mimon Nov 06 '19 at 14:22