javascript open new window with html content

How to Open a New Window with HTML Content using JavaScript

Opening a new window with HTML content using JavaScript can be quite useful in many situations. For instance, you can use it to display a form or a table that needs more space than the main window allows. Here's how you can do it:

Method 1: Using the window.open() Method

The easiest way to open a new window with HTML content using JavaScript is by using the window.open() method. This method opens a new browser window with the specified HTML content. Here's an example:

window.open("data:text/html,<html><body><h1>Hello, world!</h1></body></html>");

In the example above, we're opening a new window with the HTML content "<html><body><h1>Hello, world!</h1></body></html>". Notice that we're using the "data:" URI scheme to specify the content type of the HTML document.

You can also pass additional parameters to the window.open() method to customize the behavior of the new window. For instance, you can specify the width and height of the new window, whether or not it should have scrollbars, and so on. Here's an example:

window.open("data:text/html,<html><body><h1>Hello, world!</h1></body></html>", "_blank", "width=400,height=400,scrollbars=yes");

In the example above, we're opening a new window with the same HTML content as before, but we're also specifying that the new window should be 400 pixels wide and 400 pixels tall, and that it should have scrollbars.

Method 2: Using the document.write() Method

Another way to open a new window with HTML content using JavaScript is by using the document.write() method. This method allows you to write HTML directly to the document. Here's an example:

var popupWindow = window.open("", "popupWindow", "width=400,height=400");
popupWindow.document.write("<html><body><h1>Hello, world!</h1></body></html>");
popupWindow.document.close();

In the example above, we're opening a new window with no content using the window.open() method. Then, we're writing the HTML content directly to the new window using the document.write() method. Finally, we're closing the document using the document.close() method.

Notice that we're also specifying a name for the new window ("popupWindow") and some parameters to customize its behavior (width=400, height=400).

Conclusion

Opening a new window with HTML content using JavaScript can be done in many ways. In this article, we've seen two different methods: using the window.open() method and using the document.write() method. Depending on your specific use case, one method might be more suitable than the other.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe