0

I am trying to show text fetched from local file on the chrome browser, but it does not show up.

I run the script on localhost. The code is as follows:

var target = document.getElementById("my-element");
var content = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "content.txt");
xhr.onload = () => {
  content = xhr.response.split(/\r?\n/);
  let counter = 0;
  setInterval(() => {
    target.innerHTML = content[counter++ % content.length];
    setTimeout(() => target.innerHTML = "", 500);
  }, 1000);
};
xhr.send();
<div>
  <span id="my-element" class=" css-1yy09vp" data-font-weight="semibold"></span>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
yusuf
  • 3,591
  • 8
  • 45
  • 86
  • 1
    Local file from where? – evolutionxbox Jan 18 '22 at 13:03
  • from my computer – yusuf Jan 18 '22 at 13:03
  • 1
    Is the file being served by a server (locally)? – evolutionxbox Jan 18 '22 at 13:04
  • The file is under the same folder with the html file. – yusuf Jan 18 '22 at 13:07
  • 1
    That doesn’t mean it’s available to the browser. Remember, the browser doesn’t have direct access to your computer folders. The file needs to be served by a server – evolutionxbox Jan 18 '22 at 13:09
  • How can I do it? The browser has access to my html files, why not to the text file? – yusuf Jan 18 '22 at 13:11
  • 3
    `XMLHttpRequest` works with http(s) protocol, if you're opening an html file using file protocol, you can't make a XMLHttpRequest to a relative URL, because that contains the file protocol. You've to install a server to your local machine to get XMLHttpRequests to work, or use [FileReader API](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) instead. – Teemu Jan 18 '22 at 13:14
  • What would be the proper command for that? I need to read text from the file, and keep it line by line in an array. – yusuf Jan 18 '22 at 13:15
  • 1
    Alternatively save a js object or string and load it like this: ` ` where content.js is `const txt = \`content here\nmore lines\nevven more lines\`` – mplungjan Jan 18 '22 at 13:36
  • 1
    @yusuf Maybe not worth of nothing, but Majid Laissi'd answer in the linked dup does not work anymore in modern browsers. I've last seen it working in Firefox around the end of 2017, after that non of the modern browsers has supported file protocol with XHR requests to the local file systems. – Teemu Jan 18 '22 at 14:27
  • Thank you for the answer, @mplungjan. However, it shows the whole text file. I want each the text at each line blink one by one, sequentially. – yusuf Jan 18 '22 at 14:35
  • So merge them: `const target = document.getElementById("my-element"), content = txt.split(/\r?\n/); let counter = 0; setInterval(() => { target.innerHTML = content[counter++ % content.length]; setTimeout(() => target.innerHTML = "", 500); }, 1000);` – mplungjan Jan 18 '22 at 14:38

0 Answers0