How to Open an HTML File Using JavaScript?

Estimated read time 1 min read

You can’t directly open an HTML file using JavaScript because JavaScript runs in a web browser, not on the file system.

However, you can use JavaScript to open an HTML file in a web browser by creating an anchor <a> element with a href attribute set to the URL of the HTML file, and a target attribute set to _blank. Then, you can use JavaScript to dynamically add the anchor element to the document and trigger a click event on it to open the HTML file in a new tab.

Here’s an example:

<button onclick="openFile()">Open File</button>

<script>
  function openFile() {
    let fileUrl = "https://www.example.com/file.html";
    let a = document.createElement("a");
    a.href = fileUrl;
    a.target = "_blank";
    a.click();
  }
</script>

In this example, clicking the “Open File” button will dynamically create an anchor element with the href attribute set to the URL of the HTML file and the target attribute set to _blank, and then trigger a click event on it to open the HTML file in a new tab.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply