Since this is a Google Chrome extension, you are not associated with the same origin policy.
Basically, you will need content scripts to get all the images on the page and check each image size in the DOM to see if it is larger - the last image extracted.
You can use Message Passing to communicate with Script Content on a pop-up / background page.
For example, I will show you how to get the largest image from a page and show it in a popup window. We use all the methods shown above, and you will see the largest image in the pop-up window if you activate it. (must show that I believe :))
manifest.json (fragment)
... "permissions": [ "tabs", "http://*/*" ], "content_scripts": [ { "matches": ["http://*/*"], "js": ["images.js"], "run_at": "document_start", "all_frames": true } ] ...
popup.html
<!DOCTYPE html> <html> <head> <script> function getImage() { chrome.tabs.getSelected(null, function(tab) { chrome.tabs.sendRequest(tab.id, {method: "getImage"}, function (response) { var text = document.getElementById('image'); var image = response.data; text.src = image ? response.data : 'no_image.gif'; }); }); } </script> </head> <body> <button onclick="getImage(); ">Get Largest Image</button> <img src="no_image.gif" id="image"/> </body> </html>
images.js (script content)
function getMaxImage() { var maxDimension = 0; var maxImage = null; // Iterate through all the images. var imgElements = document.getElementsByTagName('img'); for (var index in imgElements) { var img = imgElements[index]; var currDimension = img.width * img.height; if (currDimension > maxDimension){ maxDimension = currDimension maxImage = img; } } // Check if an image has been found. if (maxImage) return maxImage.src; else return null; } // Listen for extension requests. chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (request.method == "getImage") { sendResponse({data: getMaxImage()}); } else { sendResponse({}); // snub them. } });
Mohamed mansour
source share