Ryewell
Ryewell

Reputation: 49

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?

Upvotes: 1

Views: 1818

Answers (2)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

Example using JQuery $.get()

if (permission === "granted") {
  $.get("notificion.text", function(data) {
    var notification = new Notification("Hi there", {
      icon: "icon.jpg",
      dir: "ltr",
      body: data
    });
  });
}

Upvotes: 0

SeinopSys
SeinopSys

Reputation: 8937

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);
  };
}

Upvotes: 2

Related Questions