Search code examples
javascriptjsonwindow.open

How To Set a .json file as a variable for use in window.open (javascript)?


I have made a website using html and javascript. I am Experienced In both, but am struggling with making a button open a website with the url being from a json file. So I want to make a json file a variable, then use it with window.open(JSON-url,"_blank"). I then want to make a var called JSON-url and it must be linked with the .json file.


I had Searched up many examples, but cannot seem to get the correct wordings. I have tried w3schools, Stack Overflow, Quora and many others. I mainly tried other searches for example, "How To Make JSON a variable to use in window.open javascript", but that didn't work either.

{
  "JSON-url": "https://www.google.com"
}

I bet you there are a lot who know the answer to this, so please, raise your thoughts!


Solution

  • There's nothing special about JSON files when using a variable for the URL in window.open(). You do it the same as any other URL.

    Use the FileReader API to read the file, then use the contents as the URL to open.

    function openFile(files) {
      if (files.length == 0) {
        return;
      }
      const reader = new FileReader();
      reader.onload = function() {
        var url = reader.result.trim(); // Contents of the file
        console.log("Opening " + url);
        window.open(url, "_blank");
      }
      reader.readAsText(files[0]);
    }
    Select file:
    <input type="file" id="txt" accept="text/plain" onchange="openFile(this.files)">

    This won't work in the above snippet because Stack Snippets are sandboxed and don't allow window.open().