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" ?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With