There's a site with 10 or more images, lets say
<div class="container"><img src="some_URL"></div>
I want to generate thumbnails to them to save images into extension's storage, so that I can view them without offline or without heavy traffic. That site does not allow cross-origin use of images, so atm I'm trying to use the next "algorithm":
- Include a following script (include2page.js) to the page.
- Start cycle from 0 to number of images on the page.
- Get the visible position and size of an image.
- Scroll page to it, send coordinates via
chrome.runtime.sendMessage()
to extension's background script (background.js). - Use
chrome.tabs.captureVisibleTab()
to get a picture in background script. - Copy it to canvas, shrinking and cropping to desired thumbnail size.
- Save thumbnail into
chrome.storage.local
as base64.
include2page.js:
var list = document.getElementsByClassName('container');
for (var i = 0; i < list.length; i++) {
var img = list[i].getElementsByTagName('img')[0];
chrome.runtime.sendMessage(null, {
'type': 'imgData',
'data': {
x: img.x,
y: img.y,
w: img.width,
h: img.height
}
});
}
background.js (output to console for simplicity):
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "imgData") {
var imgData = request.data;
chrome.tabs.executeScript(null, {code: "window.scrollTo(0, "+imgData.y+");"});
chrome.tabs.captureVisibleTab(null, {format: 'png', quality: 100}, function(src) {
var canvas = document.createElement("canvas");
canvas.width = 96;
canvas.height = 96;
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = src;
image.onload = function(){
ctx.drawImage(image, imgData.x, imgData.y, imgData.w, imgData.h, 0, 0, 96, 96);
console.log(canvas.toDataURL("image/png", ""));
}
});
});
But there's a problem: due to asynchronous nature of extension's functions it doesn't work that well in a continuous cycle, I can get 2-3 thumbnails assign to all of the images, i.e. different images generate are getting one thumbnail.
Maybe there's some simpler solution? Or, if there isn't, how can I replace a cycle?