2

私はクロムでプッシュ通知システムを作成しようとしています。 私は、mysqlからデータをフェッチしてJSONをエコーするphpを持っています。今は、プッシュ通知が到着してJSONデータを読み込むときにアクティブになるgetJsonCode()関数を呼び出したいと思います。サービス担当者のXMLHttpRequest

サービス担当者の中で私は標準機能を作成しました。問題は、私はそれが私に語ったの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'); 
} 

を定義していないということです、それはサービス労働者の中に、このような外部ファイルを呼び出すか、制限のいくつかの種類があることは可能ですか?なぜこれが動作しないのか分かりません。

答えて

5

XMLHttpRequestの代わりに、Fetch APIを使用することができます。 XMLHttpRequestは推奨されておらず、サービスワーカスコープでは利用できません。

this ServiceWorker Cookbook recipeに達成したいことの例があります。

+0

ありがとう、fetch worked :) –

2

fetch()はXHRに似たリクエストをすることができますが、よりシンプルでフレンドリーなAPIを持つ新しいAPIであるため、XHRの代わりに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 

    }); 
})); 
}); 
関連する問題