Search code examples
javascripthtmltypescriptdata-uri

How to open a string as a HTML content in a new tab?


public openNewTab(blob: Blob | string) {
   const data = 'data:text/plain;charset=utf-8,' + encodeURIComponent(blob);
   window.open(data, '_blank');
   setTimeout(() => window.URL.revokeObjectURL(data), 100);
}

I'm trying to open blob file (in this example it's a string) into a new tab as a HTML content. This function works fine but it opens a plain text content and tags are just written like "<html><head><title>...." as a text. I want to display the HTML content. I tried to define data as text/html but it doesn't work. How can I do that without using any library? Also I tried to use anchor tag like this;

   const anchorElement = document.createElement('a');
   document.body.appendChild(anchorElement);
   anchorElement.setAttribute('href', data);
   anchorElement.setAttribute('target', '_blank');
   anchorElement.click();

It has same result with window.open().


Solution

  • You are telling the browser the content is text/plain - thats why it's handled as text only. Change it to text/html and it should work.

    As an alternative you can set the content of opened window with window.document.write().

    document.querySelector("#someButton").onclick = function() {
      let child = window.open("about:blank","myChild");
      child.document.write(`<html>
        <head><title>Hi mum!</title></head>
        <body><p>Hello World</p></body>
       </html>`);
      child.document.close();
    }
    

    Working fiddle.