Reputation: 15336
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
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?
Upvotes: 4
Views: 2713
Reputation: 163262
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.
Upvotes: 2