search

Home  >  Q&A  >  body text

Open calculation documents using window.open() and data: scheme

I have a web page that runs in a browser that generates a computed HTML document that I want to open in a new browser tab.

The easy and dirty way is to do this:

const w = window.open('', '_blank');
w.document.open();
w.document.write(htmlContents);
w.document.close();

Very simple. But this has some awkward consequences that I don't like. That is, the new tab's URL must point somewhere, but since the new document is calculated dynamically, there is no to point to it. If I don't specify a URL, it will use the URL of my web page. So if someone refreshes the tab containing the generated document, the document disappears and a new instance of my webpage is loaded in its place. This can confuse users.

I think what suits my needs better is to use data URIs. I simply encode the entire content of the web page into the URI itself, and then open the URI using window.open(). It's ugly, but semantically consistent with my goal: a self-contained computational document that can't be accidentally navigated out on page refreshes.

I constructed a concept for this that I think is very simple, as follows:

const doc = encodeURIComponent('<html><body><p>Hello, world!</p></body></html>');
window.open(`data:text/html;charset=utf-8,${doc}`, '_blank');

If I run this code, a new window flashes on the screen for one frame and then closes immediately. No errors occurred.

What did i do wrong?

P粉752479467P粉752479467229 days ago564

reply all(1)I'll reply

  • P粉085689707

    P粉0856897072024-04-07 09:10:30

    Apparently all modern browsers intentionally and explicitly prevent the use of such data URIs. marvelous.

    Another tick on the blackboard is "The perfect thing I needed was recently taken away from us." Well.

    On the plus side, this seems to do everything I want better:

    const html = '

    Hello, world!

    '; const blob = new Blob([html], { type: 'text/html'}); const url = URL.createObjectURL(blob); window.open(url, '_blank');

    reply
    0
  • Cancelreply