服务工作者中的XMLHttpRequest

eli*_*nti 4 php json push-notification google-cloud-messaging service-worker

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

在我的服务工作者中,我创建了标准函数.问题是,当我使用XMLHttpRequest创建getJsonCode时,它告诉我它没有定义

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');
}
Run Code Online (Sandbox Code Playgroud)

是否可以在服务工作者中调用这样的外部文件,或者是否存在某些限制?因为我不知道为什么这不起作用

Mar*_*rco 5

XMLHttpRequest您可以使用新的Fetch API代替.XMLHttpRequest已弃用,在服务工作者范围内不可用.

这个ServiceWorker Cookbook配方中有一个确切想要实现的示例.

  • @AbhinavSingi 是的,我已经在回复的第二句中写下了这一点。 (2认同)
  • @nvirth 对于普通工人来说是这样,但对于服务人员来说则不然。XMLHttpRequest 没有向服务工作人员公开,在规范 (https://xhr.spec.whatwg.org/) 中,您可以看到 `[Exposed=(Window,DedicatedWorker,SharedWorker)]`。如果您不相信,请查看 https://github.com/whatwg/xhr/issues/19、https://www.fxsitecompat.dev/en-CA/docs/2015/xmlhttprequest-is-no-更长可用的服务工作人员/,https://bugzilla.mozilla.org/show_bug.cgi?id=931243。 (2认同)

R C*_*R C 5

您可以使用 fetch() 而不是 XHR,因为 fetch() 是一个新的 API,它允许您发出类似于 XHR 的请求,但具有更简单/友好的 API。在此处阅读有关 fetch 的更多信息。尝试这个:-

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
    
    });
}));
});
Run Code Online (Sandbox Code Playgroud)