1

so i am using a local html and javascript file as a gui for video files. It is pretty much a take-away version of my server index.php for them to use elsewhere. Everything works fine, but i am trying to load content from a txt file. My webserver uses XMLHttpRequest to retrieve it, as it is server side. But since the takeaway version isn't on the server, the text file resides in the same local directory as the html file

function loadBookmarks(){
  var infoDoc = new XMLHttpRequest()
  infoDoc.open("GET","info.bk");
  infoDoc.send();
  infoDoc.onreadystatechange = function() {
    if (infoDoc.readyState== 4 && infoDoc.status == 200) {
        document.getElementById("bookmarks").querySelector('p').innerHTML = infoDoc.responseText;
        document.getElementById("infoButton").style.backgroundColor = "#119933";
    } else {
        document.getElementById("bookmarks").querySelector('p').innerHTML = "";
        document.getElementById("infoButton").style.backgroundColor = "#993333"
    }
 }  
}

That is the function i am using. Is there another way to get the text from the file with an offline non server javascript file?

Mitchell

Mitchell Day
  • 196
  • 2
  • 14
  • how do you execute your javascript ? If it's on a browser, I don't think it can access to your directory. – Bdloul May 03 '18 at 23:04
  • By 'local' you mean that you are using `file://` or some "custom type" protocol. So it won't work on Chrome and similar browser due to "securiity restrictions". It shouldwork on Firefox though: https://stackoverflow.com/a/38757037/4146962 – Sanxofon May 07 '18 at 18:07

1 Answers1

0

It's more a workaround and it involves some constraints but depending on your goals it may fit your needs. Or not.

AFAIK you won't be able to achieve this with XmlHttpRequest but you can use a FileReader to load your file. You can find a working example in this SO

How to open a local disk file with Javascript?


Downside is that FileReader has to be triggered from a manual interaction. So you won't be able to load your file without a user ( YOU ) clicking and browsing the file to be loaded.

Could you deal with it ?

If so, it's even not that worse, because once it has been loaded, just put the content of the file into the localeStorage, so the next time loading the page, or refreshing the page, the data from the file could comes from the localeStorage, and you won't have to select manually the file to be loaded again. Except of course if the file has changed, but as you are not on a server/webserver, odds are low that the file will change automatically. So I will guess that if you have to change the file manually you could also accept one more manual intervention.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage


In case it wasn't already your choice, consider using JSON formatted text in the file and also in the localeStorage, it could simplify your data transformations.


[EDIT] And of course if your file has never going to change, just embed your data into a javascript variable.

[EDIT 2] Example

<body>
    <!-- The input widget to select a file from browse -->
    <input type="file" id="file-input" />

    <!-- testing purpose only, a markup to display the loaded file content -->
    <h3>Loading a file:</h3>
    <pre id="file-content"></pre>
    <script>

    // Place a listener to know when the page is loaded
    window.addEventListener('load',function(e){
      // If there is some persistent data on the browser called 'stored_data'
      if( localStorage.getItem('stored_data')){
        // We can do something with this data
        // without asking a user interaction at first
        // User interaction could be done in order to refresh the data ( file changed since storing in browser cache )
        doSomethingWithFileContents();
      }
    });

    /**
     * This is the callback of the addEventListener, it will be executed each time user select a file
     * It's linked below, on the addEventListener call
     */
    function readSingleFile(e) {
      //retrieve the first selected file the user has select
      var file = e.target.files[0];

      // If no file selected, abort this function execution
      if (!file) {
        return;
      }
      // If a file is selected, create a new file reader
      var reader = new FileReader();

      // Define a callback to be run when the file will be loaded
      reader.onload = function(e) {

        // You can still use some console.log for debugging purpose
        //console.log(e);

        // Retrive the content of the loaded file
        var contents = e.target.result;

        // To enable some persistency, store the contents into a localeStorage
        // It means next time you load the page, the data could come from the browser cache
        localStorage.setItem('stored_data', contents );

        // Will can now call the logic what we need to do with the file content
        doSomethingWithFileContents();
      };

      // Trigger the file reader to load the selected file
      reader.readAsText(file);
    }

    /**
     * This function will be executed when data is ready.
     * You should implements the logic that should be run with the file data
     *
     *  - Data is ready could mean:
     *      - Data was available through localStorage
     *      - Data has just been loaded through FileReader
     */
    function doSomethingWithFileContents() {

      // Retrieve the cached data
      var loadedData = localStorage.getItem('stored_data');

      // Get the element that will display the raw data
      var element = document.getElementById('file-content');
      // Set its content to the storedData
      element.textContent = loadedData;

      // Once again, I strongly recommend you to use JSON formatted value in the file
      // It will enable some easy transformation/parsing from js side


    }

    // Place a addEventListener on the file-input id element
    // When its value changed, run the readSingleFile function
    document.getElementById('file-input').addEventListener('change', readSingleFile, false);
</script>
</body>
SwingingTom
  • 55
  • 1
  • 11
  • Thanks for that. It responding to a user action is fine. Only because the file is created at some point and then copied to that directory before the user takes it with them. How would i go about adding it to a javascript variable. And it is just a txt file with simple text (small paragraphs or a few sentences. – Mitchell Day May 07 '18 at 13:16
  • I've just added an example – SwingingTom May 08 '18 at 09:18