Reputation: 260
After hours of reading in the Google-Documentations and Stackoverflow I decided to post this question. There already are some similar ones but I haven't found a answer that really helped me. However, I'm trying to get a list of all images embeded on a page to use it in the Chrome extension. I've tried to do it with simle Javascript (document.images) but didn't get any entries. After some research I found out, that the only way to read elements from a page is using a EventListener. The function should be started using the chrome context-menu.
chrome.contextMenus.create({
title: "ExampleFunction",
contexts:["page"],
onclick: exampleFunction,
});
This part works fine, but how do I get the images after calling the function? I've tried some ways using eventlisteners and finally got this function:
function downloadImages(info,tab) {
alert('o');
chrome.extension.onRequest.addListener(function(result){
for (var i in result.images) {
allImages.push(result.images[i]);
}
alert(allImages[0]);
});
}
The first alert works perfect but everything else is just doing nothing.
Upvotes: 5
Views: 8333
Reputation: 8201
First you have to actually get the images, and the way to do that is to use a content script
. I am assuming that your onclick was a typo and that you have this instead:
chrome.contextMenus.create({
title: "ExampleFunction",
contexts:["page"],
onclick: downloadImages,
});
Then you would want to have something like this:
function downloadImages(info,tab) {
alert('o');
chrome.tabs.executeScript(tab.id,{file:"script.js"});
}
chrome.runtime.onMessage.addListener(function(message){
//In case you want to do other things too this is a simple way to handle it
if(message.method == "downloadImages"){
message.images.forEach(function(v){
allImages.push(v);
});
alert(allImages[0]);
}
});
And then for your script.js:
var images = [];
for(var i = 0; i < document.images.length; i++){
images.push(document.images[i].src);
}
chrome.runtime.sendMessage({method:"downloadImages",images:images});
This grabs the array of images and sends back the src
of each image to your background page so you can do whatever you want with it.
Upvotes: 5