4

There's a static page myapp/page.html and a static file in same directory myapp/data.txt. I would like to open that page in Browser from the file system, without web server, and get content of the myapp/data.txt file. It should be possible periodically reload that file to check if its content changed.

  • fetch('file:///myapp/data.txt') is not working because of some security error Fetch API cannot load file:///myapp/data.txt
  • Loading as an image img.src='data.txt' also not working, it loads the file it could be seen in the networking tab, but when you try to read it as the image content it tells that image is broken.

As a last resort it's possible to change data.txt into data.js and load it via script.src='data.js' but maybe it's somehow possible to load it as a text too?

Alex Craft
  • 13,598
  • 11
  • 69
  • 133

1 Answers1

2

As a last resort it's possible to change data.txt into data.js and load it via script.src='data.js' but maybe it's somehow possible to load it as a text too?

Yeah, you could use the old JSON-P method, but with a statically-named function.

Basically, you have in your main script something like this:

window.onDataLoad = (data) => {
  // do something with data here
}

// Inject script tag wherever you want to reload the data
const scriptEl = document.createElement('script');
scriptEl.src = 'data.js';
document.querySelector('head').appendChild(scriptEl);

Then, in your data.js, something like:

window.onDataLoad( << YOUR DATA HERE >> );

Finally... just wanted to note that I sympathize! It's ridiculous that fetch() can't handle this. What a great opportunity to abstract the fetching of data from HTTP, when moving away from XHR. Sadly, this didn't happen.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • You mention `static` **named function** where is the `static` keyword? I thought ES2015 specifies the static keyword such that static methods will be set as OwnProperty of the class constructor function. Just a question of mine for knowledge, to answer my own curiosity. – ABC Apr 02 '21 at 05:44
  • 1
    @File In this case, I intend for `static` to mean something different. Normally when you use JSON-P, the name of the function is dynamically (and ideally, randomly) generated. The client might specify `returnDataFunction123456789` to the server. The server then responds in the format `returnDataFunction123456789({...})`, calling the function specified by the client. Dynamic in the sense that the response is dynamically generated server-side. Since there is no server-side here, I'm suggesting there be a fixed function name in the "data" JavaScript file. – Brad Apr 02 '21 at 05:52
  • 1
    @File No, it isn't. Fetch doesn't work outside of HTTP. – Brad Apr 02 '21 at 05:56
  • Ah, I see thanks for the update. CORS problem, sad, should be able to handle disk requests. – ABC Apr 02 '21 at 06:03