Service Worker 中的 XMLHttpRequest

我正在尝试在 chrome 上创建一个推送通知系统.我有一个从 mysql 获取数据并回显 JSON 的 php,现在我想调用一个函数 getJsonCode(),当推送通知到达并读取 JSON 数据时它会被激活.

I'm trying to create a push notification system on chrome. I have a php that fetches data from mysql and echoes a JSON, now I'd like to call a function getJsonCode() that it's activated when a push notification arrives and reads the JSON data.

在我的 service worker 中,我创建了标准函数.问题是,当我使用 XMLHttpRequest 创建 getJsonCode 时,它​​告诉我它没有定义

Within my service worker I've created the standards functions. The problem is that when I create getJsonCode with a XMLHttpRequest it tells me it's 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');
}

是否可以在 service worker 中调用这样的外部文件,或者是否存在某种限制?因为我不明白为什么这不起作用

Is it possible to call an external file like this within a service worker or are there some kind of limitations? Because I don't get why this isn't working

推荐答案

代替 XMLHttpRequest,您可以使用新的 Fetch API.XMLHttpRequest 已被弃用,在 Service Worker 范围内不可用.

Instead of XMLHttpRequest, you can use the new Fetch API. XMLHttpRequest has been deprecated and is not available in the service worker scope.

在这个 ServiceWorker Cookbook recipe 中有一个示例,说明您想要实现的目标.

There's an example of exactly what you want to achieve in this ServiceWorker Cookbook recipe.

相关文章