Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open a open an image data url in a new tab?

I have a base64 data url for an image such as...

data:image/png;base64,iVBORw0KGgoAAAANS...

The website generates this image, and users want to open it in a new tab so they can save it.

I see some answers such as this: How to show Base64 image on browser's new tab?

But what about just opening the dataUrl in the tab itself? That way users can do Ctrl+S to save the image etc. Rather than viewing an HTML page with the image (Ctrl+S would save the html page containing the image)

How can I programmatically make the page open the data url in a new tab, as if the user right clicked -> "Open image in new tab" ?

like image 570
Carson Avatar asked Oct 18 '25 02:10

Carson


1 Answers

Recently, Chrome is blocking new tabs with data: urls. It's better to convert base64 to a Blob and open the url.

function openBase64InNewTab(data: string, mimeType: string) {
  var byteCharacters = atob(data);
  var byteNumbers = new Array(byteCharacters.length);

  for (var i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }

  var byteArray = new Uint8Array(byteNumbers);

  var file = new Blob([byteArray], {
    type: mimeType + ";base64",
  });

  var fileURL = URL.createObjectURL(file);

  window.open(fileURL, "_blank");

  URL.revokeObjectURL(fileURL);
}

openBase64InNewTab(base64, 'image/png')
like image 166
Mohamad Shiralizadeh Avatar answered Oct 19 '25 17:10

Mohamad Shiralizadeh