1

I have a script which converts a canvas element to an <img>tag and then reloads it in a new window (about:blank page). If I then right-click the image and select 'Open Image In New Tab' it opens the Base64 DataURL (i.e. Just the image).

Is there any way to open the Base64 DataURL without the user having to right-click the image?

Ideally, the user would never even see the about:blank page and would simply be redirected to the DataURL.

Here is the current code that generates the image and opens it in a new window:

<script>
function print_card(){
    var canvas=document.getElementById("canvas");
    var win=window.open();
    win.document.write("<img id='compiledImg' src='"+canvas.toDataURL('image/png')+"' width='324' height='204' style='margin: 0; padding: 0; background: #e6e6e6;'/>");
    win.location.assign(reload);
}

$("#printCard").click(function(){ print_card(); });
    </script>

It seems like I should be able to get the dataURL from the image id and redirect to it as opposed to a new window, but I have no idea how to accomplish it.

I tried assigning canvas.toDataURL('image/png) to win.location but that did not help.

Any guidance would be much appreciated.

5150 Design
  • 179
  • 14
  • Most modern browsers do not allow opening data URLs programmatically in the top frame for security reasons - see eg. [this discussion for Chromium](https://bugs.chromium.org/p/chromium/issues/detail?id=684011&desc=2). – Petr Srníček Jul 15 '19 at 13:06
  • @PetrSrníček Thanks for your response. I noticed the linked discussion does not reference opening a data URL in a print dialogue. Do you think that this would be possible? – 5150 Design Jul 15 '19 at 13:39

1 Answers1

3

It seems that you are simply trying to open the generated image in a new tab. Most modern browsers do not allow opening data URLs programmatically in the top frame for security reasons, you need to use a different method, eg. a blob like this:

function openCanvasContentInNewWindow(canvas) {
  canvas.toBlob(blob => {
    const objectURL = URL.createObjectURL(blob);
    window.open(objectURL);
  }, 'image/png');
}

Reference for the HTMLCanvasElement.toBlob method.

If you need to support browsers that do not support HTMLCanvasElement.toBlob() (such as Edge and older browsers), you can use this polyfill. (Since I am not the author of the polyfill, I am not sure whether it would be OK for me to paste the code here directly.)

Petr Srníček
  • 2,296
  • 10
  • 22