例如,如果我输入:
http://www.google.com/
http://www.google.com/
它将返回:
http://www.google.com/images/logos/ps_logo2.png
使用javascript / jquery.这些网站都是外部的.谢谢!
解决方法
由于这是Google Chrome扩展程序,因此您不受同一原始政策的约束.
基本上,您需要content scripts来获取页面中的所有图像,并检查DOM中每个图像的大小,以了解它的最大提取图像是否更大.
您可以使用Message Passing从内容脚本与弹出/背景页面进行通信.
例如,我将向您展示如何从页面获取最大的图像并在弹出窗口中显示它.我们使用上面显示的所有技术,如果您激活它,您将看到弹出窗口中的最大图像. (应该表明我相信:))
manifest.json(片段)
... "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(内容脚本)
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. } });