Include data URLs for images in content snapshots
Opened this issue · 0 comments
mfulton26 commented
Something like the following:
function imgToDataUrl(img, callback) {
function imageUrlToDataUrl(url, callback) {
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
canvas.getContext('2d').drawImage(img, 0, 0);
var rawDataUrl = canvas.toDataURL('image/png');
callback(rawDataUrl);
}
image.src = url;
}
imageUrlToDataUrl(img.src, function(rawDataUrl) {
var width = img.width;
var height = img.height;
var cssText = window.getComputedStyle(img).cssText;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var image = new Image();
var data = `<svg
xmlns="http://www.w3.org/2000/svg"
width="${width}"
height="${height}"
>
<foreignObject
width="100%"
height="100%"
>
<img
xmlns="http://www.w3.org/1999/xhtml"
width="${width}"
height="${height}"
src="${rawDataUrl}"
style="${cssText.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/&/g, '&')}"
/>
</foreignObject>
</svg>`;
image.onload = function() {
canvas.getContext("2d").drawImage(this, 0, 0);
callback(canvas.toDataURL('image/png'));
}
image.src = "data:image/svg+xml," + encodeURIComponent(data);
});
}
imgToDataUrl($0, function(dataUrl) {
console.log(dataUrl);
});
Note that this will require making the remote content script asynchronous.