【发布时间】:2017-05-18 13:20:51
【问题描述】:
谷歌浏览器最新版(v55.0.2883.87) 该(sw.js)文件中有各种事件。每次文件被请求获取事件时都会发生。其他事件发生的方式和时间(同步、推送)(网络通知 API)。我想调试它。有没有可用的文档?
更新: server-key-from-firebase-console
subscription-key-after-subscribing-web-notification
发现推送通知是如何触发的--
String url = "https://fcm.googleapis.com/fcm/send";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "key=<server-key-from-firebase-console>");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "{\"to\":\"<subscription-key-after-subscribing-web-notification>\"}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
更新 2: 好的,现在我找到了如何从 google chrome 调试器工具或 javascript 在服务工作者文件中触发同步事件。下面是代码,我在google的博客post上找到的。
// Register your service worker:
navigator.serviceWorker.register('/sw.js');
// Then later, request a one-off sync:
navigator.serviceWorker.ready.then(function(swRegistration) {
return swRegistration.sync.register('myFirstSync');
});
然后在/sw.js监听事件:
self.addEventListener('sync', function(event) {
if (event.tag == 'myFirstSync') {
event.waitUntil(doSomeStuff());
}
});
【问题讨论】:
-
您也可以收听通知:
self.addEventListener('push', (event) => { });。例如,当您通过 Firebase Notifications 发送通知时,会引发通知。
标签: push-notification google-cloud-messaging service-worker