我正在使用网络推送php librairie做自己的通知系统。一切都可以在Firefox上运行,但是Chrome和Opera出现了问题。事实是event.data.text()在我的服务工人上为空...
正如您在PushToServiceWorker.php上看到的那样,我将有效负载传递给通知,并且可以使用service-worker.js上的event.data.text()获取数据。由于与我的浏览器不兼容,我进行了curl调用以使用Chrome发送通知,但是当我尝试在$ fields上也发送有效负载时,在service-worker.js上,event.data.text()为null。我该如何使用cURL来获取event.data.text()的价值?
PushToServiceWorker.php(Firefox部分)
$notifications = array(
array(
'subscription' => Subscription::create(array(
'endpoint' => $endpoint, // Firefox 43+,
'publicKey' => $publicKey, // base 64 encoded, should be 88 chars
'authToken' => $authToken // base 64 encoded, should be 2
)
),
'payload' => $roomId
),
);
$webPush = new WebPush();
foreach ($notifications as $notification) {
$webPush->sendNotification(
$notification['subscription'], $notification['payload'] // optional (defaults null)
);
}
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
echo "[v] Message sent successfully for subscription {$endpoint}.";
} else {
echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}
service-worker.js
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log("[Service Worker] Push had this data: ",event.data.text());
var roomId = event.data.text();
console.log(roomId);
const title = 'Partage d\'écran';
const options = {
body: 'Quelqu\'un souhaite que vous partagiez votre écran'
// icon: '../images/icon.png'
};
self.addEventListener('notificationclick', function(event) {
// console.log('On notification click: ', event.notification.tag);
event.notification.close();
...
PushToServiceWorker.php(Chrome)
$url = substr($endpoint,0,strrpos($endpoint,'/'));
$regids = substr(strrchr($endpoint, '/'),1);
$fields = array(
'to' => $regids,
'payload' => $roomId
);
$headers = array('Authorization: key=SERVER KEY', 'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
print_r(json_encode($fields));
$result = curl_exec($ch);
echo $result;
if ($result == FALSE) {
die('Curl Failed');
}
curl_close($ch);
}