【问题标题】:XMLHttpRequest within service worker服务工作者中的 XMLHttpRequest
【发布时间】:2016-09-03 21:22:55
【问题描述】:

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

在我的 Service Worker 中,我创建了标准函数。问题是当我使用 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');
}

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

【问题讨论】:

    标签: php json push-notification google-cloud-messaging service-worker


    【解决方案1】:

    您可以使用新的Fetch API,而不是XMLHttpRequestXMLHttpRequest 已被弃用,在 service worker 范围内不可用。

    this ServiceWorker Cookbook recipe 中有一个您想要实现的示例。

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      相关资源
      最近更新 更多