<script type="text/javascript">
async function send() {
const vapidPublicKey = '{{ swToken }}';
let urlBase64ToUint8Array = (base64String) => {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, "+")
.replace(/_/g, "/");
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
// Register Service Worker
const register = await navigator.serviceWorker.register(
"/sw.js",
);
{% if user %}
// Register Push
const subscription = await register.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),
});
// Send Push Notification
let sub = JSON.parse(JSON.stringify(subscription));
if(sub && sub.keys){
const isIOS = () => {
return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
}
let data = {
endpoint: sub.endpoint,
token: sub.keys.p256dh,
auth: sub.keys.auth,
platform: isIOS() ? 'ios' : 'other'
};
const headers = new Headers();
headers.append("Content-Type", "application/json");
const request = new Request("{{ path('registerNotifyAuth') }}", {
method: "POST",
headers: headers,
body: JSON.stringify(data),
});
fetch(request).then((response) => {
}).then((response) => {
}).catch((error) => {
console.error(error);
});
}
{% endif %}
}
if ("serviceWorker" in navigator) {
send().catch((err) => console.error(err));
}
</script>