103

How would I open a new window in JavaScript and insert HTML data instead of just linking to an HTML file?

8 Answers 8

171

I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).

Use innerHTML instead

var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";
Sign up to request clarification or add additional context in comments.

7 Comments

Will the body object be present on a newly created window?
Yes, it is always present on any page, even if you don't put it, the browser will auto-add it
Please note that if you have <script> tags inside that HTML they will not be executed.
I am opening the window like this: var win = window.open("", "Page Help", "newwindow", "width=1100, height=700, top=100, left=100"); win.document.body.innerHTML = "help_text"; But the window is full screen and has no title. Why is it not respecting my settings?
@LarryMartell Try using the <title> tag inside win.document.head.innerHTML
|
50

You can use window.open to open a new window/tab (according to browser setting) in JavaScript.

By using document.write you can write HTML content to the opened window.

1 Comment

Also call document.close() after write() in case you have embedded JS event handler as this will trigger DOMContentLoad events.
38

Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:

https://codepen.io/trusktr/pen/mdeQbKG?editors=0010

This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):

const winHtml = `<!DOCTYPE html>
    <html>
        <head>
            <title>Window with Blob</title>
        </head>
        <body>
            <h1>Hello from the new window!</h1>
        </body>
    </html>`;

const winUrl = URL.createObjectURL(
    new Blob([winHtml], { type: "text/html" })
);

const win = window.open(
    winUrl,
    "win",
    `width=800,height=400,screenX=200,screenY=200`
);

2 Comments

Great solution, this really helped me out on a project where adding in an extra HTML file for the new window content would have been problematic. Just to add that it's worth including <meta charset="utf-8"> in the <head> of your HTML to ensure it will render any non-Latin characters.
To display non-html content such as pdf, this appears to be the best answer. Thanks!
33

When you create a new window using open, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document object.

Here is an example:

var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');

Comments

11

You can open a new popup window by following code:

var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');

Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";

What I will recommend is that first you create a new html file with any name. In this example I am using

newFile.html

And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag

<body id="mainBody">

Then open this file using

<script>    
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>

And add whatever you want to add in your body tag. using following code

<script>    
 var myWindow = window.open("newFile.html","newWindow","width=500,height=700");  

   myWindow.onload = function(){
     let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
   myWindow.document.getElementById('mainBody').innerHTML = content;
    } 

myWindow.window.close();
 </script>

it is as simple as that.

Comments

3

You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open

var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");

Comments

2

Use this one. It worked for me very perfect.

For New window:

new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })))

for pop-up

new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })),"width=800,height=600")

Replace HTML_CONTENT with your own HTML Code Like:

new_window = window.open(URL.createObjectURL(new Blob(["<h1>Hello</h1>"], { type: "text/html" })))

Comments

0

if your window.open() & innerHTML works fine, ignore this answer.

following answer only focus on cross-origin access exception


@key-in_short,workaround:: [for cross-origin access exception]

when you exec code in main.html -- which tries to access file window_ImageGallery.html by using window.open() & innerHTML

for anyone who encounter cross-origin access exception

and you dont want to disable/mess_around_with Chrome security policy

-> you may use query string to transfer the html code data, as a workaround.

@details::

@problem-given_situation,@problem-arise_problem::

  • say you exec following simple window.open command as other answer suggested.

    let window_Test = window.open('window_ImageGallery.html', 'Image Enlarged Window' + $(this).attr('src'), 'width=1000,height=800,top=50,left=50');
    
    window_Test.document.body.innerHTML = 'aaaaaa';
    
  • you may encounter following cross-origin access exception

    window_Test.document.body.innerHTML = 'aaaaaa'; // < Exception here
    
    Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
    

=> @problem-solution-workaround::

  • you may use query string to transfer the html code data, as a workaround. <- Transfer data from one HTML file to another

  • @eg::

    • in your main.html

        // #>> open ViewerJs in a new html window
        eleJq_Img.click(function() {
          // #>>> send some query string data -- a list of <img> tags, to the new html window
          // @repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
          let id_ThisImg = this.id;
          let ind_ThisImg = this.getAttribute('data-index-img');
      
          let url_file_html_window_ImageGallery = 'window_ImageGallery.html'
            + '?queryStr_html_ListOfImages=' + encodeURIComponent(html_ListOfImages) 
            + '&queryStr_id_ThisImg=' + encodeURIComponent(id_ThisImg)
            + '&queryStr_ind_ThisImg=' + encodeURIComponent(ind_ThisImg);
      
          // #>>> open ViewerJs in a new html window
          let window_ImageGallery = window.open(url_file_html_window_ImageGallery, undefined, 'width=1000,height=800,top=50,left=50');
        });
      
      
    • in your window_ImageGallery.html

      window.onload = function () {
        // #>> get parameter from URL
        // @repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
        // https://stackoverflow.com/questions/17502071/transfer-data-from-one-html-file-to-another
        let data = getParamFromUrl();
      
        let html_ListOfImages = decodeURIComponent(data.queryStr_html_ListOfImages);
        let id_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_id_ThisImg);
        let ind_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_ind_ThisImg);
      
        // #>> add the Images to the list
        document.getElementById('windowImageGallery_ContainerOfInsertedImages').innerHTML = html_ListOfImages;
      
        // -------- do your stuff with the html code data 
      
      };
      
      function getParamFromUrl() {
        let url = document.location.href;
        let params = url.split('?')[1].split('&');
        let data = {};
        let tmp;
        for (let i = 0, l = params.length; i < l; i++) {
          tmp = params[i].split('=');
          data[tmp[0]] = tmp[1];
        }
        return data
      }
      

@minor-note::

  • (seems) sometimes you may not get the cross-origin access exception

    • due to, if you modify the html of 'window_ImageGallery.html' in main.html before window_ImageGallery.html is loaded

      • above statement is based on my test

        & another answer -- window.open: is it possible open a new window with modify its DOM

      • if you want to make sure to see that Exception,

        you can try to wait until the opening html window finish loading, then continue execute your code

        @eg::

        • use defer() <- Waiting for child window loading to complete

          let window_ImageGallery = window.open('window_ImageGallery.html', undefined, 'width=1000,height=800,top=50,left=50');
          
          window_ImageGallery.addEventListener("unload", function () {
            defer(function (){
              console.log(window_ImageGallery.document.body); // < Exception here
            });
          });
          
          function defer (callback) {
              var channel = new MessageChannel();
              channel.port1.onmessage = function (e) {
                  callback();
              };
              channel.port2.postMessage(null);
          }
          
          
        • or use sleep() with async What is the JavaScript version of sleep()?

          eleJq_Img.click(async function() {
            ...
            let window_Test = window.open( ...
            ...
            await new Promise(r => setTimeout(r, 2000));
            console.log(window_Test.document.body.innerHTML); // < Exception here
          });
          
          
    • or you get null pointer exception

      if you try to access elements in window_ImageGallery.html


  • @minor-comment::

    There are too many similar Posts about the cross-origin issue. And there are some posts about window.open()

    Idk which post is the best place to place the answer. And I picked here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.