Skip to content
This repository has been archived by the owner on Feb 21, 2022. It is now read-only.

Include data URLs for images in content snapshots #10

Open
mfulton26 opened this issue May 18, 2018 · 0 comments
Open

Include data URLs for images in content snapshots #10

mfulton26 opened this issue May 18, 2018 · 0 comments

Comments

@mfulton26
Copy link
Owner

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, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/&/g, '&amp;')}"
    />
  </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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant