Ryewell Ryewell - 28 days ago 7
Javascript Question

Get the contents of a text file into a javascript variable

I'm working with a desktop notification. I'm using this code to show it, and its working fine:

// If the user is okay, let's create a notification
if (permission === "granted") {
var options = {
body: "This is the body of the notification",
icon: "icon.jpg",
dir : "ltr"
};
var notification = new Notification("Hi there",options);
}


But how can I fetch data from a text file into
options.body
?

Answer

Adapting the code from this answer, the finished result should look like this:

// If the user is okay, let's create a notification
if (permission === "granted") {
  var options = {
    icon: "icon.jpg",
    dir : "ltr"
  };
  var XHR = new XMLHttpRequest();
  XHR.open("GET", "notificion.txt", true);
  XHR.send();
  XHR.onload = function (){
    options.body = XHR.responseText;
    var notification = new Notification("Hi there",options);
  };
}
Comments