XMLHttpRequest in service

I am trying to create a push notification system on chrome. I have php that retrieves data from mysql and echoes JSON, now I would like to call the getJsonCode () function, which is activated when a push notification arrives and the JSON data is read.

Inside my service worker, I created the functions of the standards. The problem is that when I create getJsonCode with XMLHttpRequest, it tells me that it is not defined

self.addEventListener('install', function(event) { self.skipWaiting(); console.log('Installed', event); }); self.addEventListener('activate', function(event) { console.log('Activated', event); }); self.addEventListener('push', function(event) { console.log('Push message', event); getJsonCode(); ); }) getJsonCode() { codeRequest= new XMLHttpRequest(); codeRequest.open('get', 'myfileWithJson.php', true); codeRequest.send(); dataJSON = codeRequest.responseText; console.log('rispostaJSON'); } 

Is it possible to call an external file, for example, in an official, or are there any restrictions? Because I do not understand why this is not working.

+2
source share
2 answers

Instead of XMLHttpRequest you can use the new Fetch API . XMLHttpRequest deprecated and unavailable in the desktop area.

Here is an example of what you want to achieve in this Cookbook recipe in ServiceWorker .

+5
source

You can use fetch () instead of XHR, since fetch () is a new API that allows you to create queries similar to XHR, but has a simpler and more friendly API. Read more about fetch here . Try the following: -

 self.addEventListener('push', function(event) { console.log('Push message', event); event.waitUntil( fetch('/myfileWithJson.php').then(function(response){ return response.json(); }).then(function(data){console.log(data); return self.registration.showNotification(data.title, { body: data.body, icon: 'images/icon.png', tag: data.url }); })); }); 
+2
source

All Articles