1

I have a mobile app that needs to receive notifications via POST using OneSignal API. I was testing it on Postman and everything went just fine. Now what i want to do is: Grab a javaScript snippet and consume the OneSignal API to send my mobile any push notification. Now i am trying to do it using an example on w3Schools, but it doesn't seem to work. This is how i was trying to do it:

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "https://onesignal.com/api/v1/notification", true);
  xhttp.setRequestHeader("Content-type", "application/json");
  xhttp.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxxxxx");
  xhttp.send({
        "app_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxx",
        "contents": {"en": "Hello World!"} ,
        "included_segments" : ["All"]
});
}
</script>

</body>
</html>

I can't really understand how am i supposed to do it.

xnok
  • 299
  • 2
  • 6
  • 35
  • The Basic part - I presume you have used btoa to encode user:password. Something akin to this link https://stackoverflow.com/a/5507289/495157 – JGFMK Sep 22 '18 at 13:30
  • im not dealing with passwords here, its just that the fields don't matter – xnok Sep 22 '18 at 20:47

1 Answers1

3

Nowadays, the Fetch API is preferred over XHR. It comes with the browser, and there are lightweight polyfills.

const handleAsText = response => response.text();

const demo = document.getElementById("demo");

const displayResponse = responseText => demo.textContent = responseText;

function loadDoc() {
  const method = "POST";
  const headers = {
    "Content-type": "application/json",
    "Authorization": "Basic xxxxxxxxxxxxxxxxxx",
  }

  const body = JSON.stringify({
    "app_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxx",
    "contents": {"en": "Hello World!"} ,
    "included_segments" : ["All"],
  }) 

  return fetch("https://onesignal.com/api/v1/notification", {method, headers, body})
    .then(handleAsText)
    .then(displayResponse);
}
Benny Powers
  • 5,398
  • 4
  • 32
  • 55
  • how do you setup the title on the notification as "contents" is the body message? – Alberto Jul 02 '19 at 10:58
  • The body is just a string of JSON, so you can interpolate anything you want into it. `const body = JSON.stringify({ app_id, included_segments, contents: { en: "hi", notification: 'something' }})` – Benny Powers Jul 03 '19 at 16:29