服务工作者内的XMLHttpRequest [英] XMLHttpRequest within service worker

查看:121
本文介绍了服务工作者内的XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在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');

$ / code>

是否可以在服务人员中调用这样的外部文件或有一些限制?因为我不明白为什么这种方式不起作用。 XMLHttpRequest ,您可以使用新的取阅API XMLHttpRequest 已被弃用,并且在服务人员范围中不可用。



有一个恰好您想要的示例在 ServiceWorker Cookbook食谱中实现。


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.

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

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

解决方案

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

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

这篇关于服务工作者内的XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆