Reputation: 61
The content script is fairly simple: send all images and change there source from the background script answer:
let imgs = document.getElementsByTagName('img');
for(let img of imgs){
chrome.runtime.sendMessage({imgsrc:img.src,imgw:img.width,imgh:img.height}, function(response) {
img.src = response.canvasurl;
});
}
The background script is simple too:
chrome.runtime.onMessage.addListener(
async function(request, sender, sendResponse) {
let tmp_img = document.createElement("img");
tmp_img.width = request.imgw;
tmp_img.height = request.imgh;
tmp_img.src = request.imgsrc;
let canvas = document.createElement("CANVAS");
let ctx = canvas.getContext("2d");
canvas.width = request.imgw;
canvas.height = request.imgh;
ctx.drawImage(tmp_img, 0, 0);
sendResponse({canvasurl: canvas.toDataURL()});
});
But it just blank out all images (the canvas URL that is returned is empty canvas). Any idea what is happening?
Upvotes: 1
Views: 145
Reputation: 61
As Michael Radionov pointed out i had to let the images load first but that was not enough I also had to change it to this format:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
all_of_the_async_logic(request,sendResponse);
return true;
});
that way i could tell the connection to wait for response (using return true and dropping the async in the listener)
Upvotes: 1