2016-07-15 107 views
5

我想使用AJAX檢索我想要在用戶端顯示的推送通知的詳細信息,但它不起作用。服務工作者和AJAX

/* 
* 
* Push Notifications codelab 
* Copyright 2015 Google Inc. All rights reserved. 
* 
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
*  https://www.apache.org/licenses/LICENSE-2.0 
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed under the License is distributed on an "AS IS" BASIS, 
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied. 
* See the License for the specific language governing permissions and 
* limitations under the License 
* 
*/ 

// Version 0.1 

//'use strict'; 

console.log('Started', self); 

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

    var title = 'Push message'; 
    var xhttp = new XMLHttpRequest(); 

    xhttp.open("GET", "https://www.domain.nl/devtest/1.php", false); 
    xhttp.send(); 
    title = xhttp.responseText; 

    event.waitUntil(
     self.registration.showNotification(data, { 
      'body': 'The Message', 
      'icon': 'images/icon.png' 
     }) 
    ); 
}); 

當我使用GCM來推送通知發送到客戶端,瀏覽器提供了對服務人員這個錯誤:

sw.js:39未捕獲的ReferenceError:XMLHttpRequest的是沒有定義

+0

[服務工作者中的XMLHttpRequest]從服務人員(http://stackoverflow.com/questions/37112425/xmlhttprequest-within-service-worker) – Marco

回答

9

XMLHttpRequest已被棄用,並且在Service Worker範圍內不可用。而不是XMLHttpRequest,您可以使用Fetch API

+1

他們嚴肅地除去常規阿賈克斯的可能的複製? WTF?看起來我不會長期使用它。 –

+0

@MichaelHanon,是的,它的真實,取指是唯一的方法。另請參閱https://stackoverflow.com/a/46727718/632951 – Pacerier

+0

https://www.fxsitecompat.com/en-CA/docs/2015/xmlhttprequest-is-no-longer-available-in-service-workers/ – Pacerier

0

爲此,我們可以在fetch()選項中設置方法和主體參數。

fetch(url, { 
    method: 'post', 
    headers: { 
     "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" 
    }, 
    body: 'foo=bar&lorem=ipsum' 
    }) 
    .then(json) 
    .then(function (data) { 
    console.log('Request succeeded with JSON response', data); 
    }) 
    .catch(function (error) { 
    console.log('Request failed', error); 
    }); 

如果您想使用cookie等憑據進行提取請求,則應該將請求的憑據設置爲「include」。

fetch(url, { 
    credentials: 'include' 
}) 
+1

服務人員無法訪問cookie。 –