-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebApi_Notification_3.html
194 lines (147 loc) · 5.9 KB
/
webApi_Notification_3.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>訂閱小幫手通知功能</title>
</head>
<body>
<div style="display:none">
<button id="notificationButton">請求通知權限</button>
<button id="showNotificationButton">發送通知</button>
</div>
<input type="text" id="f_name" placeholder="您的姓名" />
<H4><div id="result"></div></H4>
<h1>請允許通知,若有設定問題,請洽相關人員</h1>
<button type="button" id="sendButton" onclick="toSaveData();" style="display:none" >訂閱訊息</button>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.4/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import { getMessaging, getToken, onMessage } from 'https://www.gstatic.com/firebasejs/10.12.4/firebase-messaging.js';
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDceaYTJF3VS20PPZDJXwnTWCGdST2yM6M",
authDomain: "learn-for-web-push-a43f1.firebaseapp.com",
projectId: "learn-for-web-push-a43f1",
storageBucket: "learn-for-web-push-a43f1.appspot.com",
messagingSenderId: "643261322701",
appId: "1:643261322701:web:e7b4a1f0b447febb92a084"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
getToken(messaging, { vapidKey: 'BLgcUwbX7qtqr_hLOIpE2Xd3yxVWc7ybWNK_UB5LR2Forp7kJA-Yx8tkGvqJueWrd3dldKUDYael33Bhmyjuqog' })
.then(token => {
console.log('FCM Token:', token);
// 將 token 發送到後端伺服器
//sendTokenToServer(token);
afterGetToken(token);
})
.catch(err => console.error('無法獲取 FCM token:', err));
</script>
<script>
function afterGetToken(tokenString)
{
var result = document.getElementById('result');
result.innerHTML = tokenString;
document.getElementById("sendButton").style.display = "block";
let selfUrl = new URL(window.location.href);
let params = selfUrl.searchParams;
if (params.has('f_name'))
{
let fName = params.get('f_name');
var f_name = document.getElementById('f_name');
f_name.value = fName;
}
toSaveData();
}
function getMachineId()
{
let machineId = localStorage.getItem('MachineId');
if (!machineId) {
machineId = crypto.randomUUID();
localStorage.setItem('MachineId', machineId);
}
return machineId;
}
function toSaveData()
{
var f_name = document.getElementById('f_name');
if (f_name.value == "" || result.innerHTML == "")
{
alert("未填姓名");
}
else
{
if (navigator.sendBeacon) {
let data = new FormData();
data.append("f_name", f_name.value);
data.append("token", result.innerHTML);
navigator.sendBeacon("https://hoaobot-liff.onrender.com/saveSubscribeData", data);
alert("已訂閱...");
let urlBackToLine = "https://line.me/R/nv/chat";
window.location.replace(urlBackToLine);
}
}
}
// 在 Push Companion 網站產生的 publickey
const publicKey = 'BLgcUwbX7qtqr_hLOIpE2Xd3yxVWc7ybWNK_UB5LR2Forp7kJA-Yx8tkGvqJueWrd3dldKUDYael33Bhmyjuqog';
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('firebase-messaging-sw.js')
.then(registration => {
console.log('Service Worker 註冊成功:', registration);
})
.catch(error => {
console.error('Service Worker 註冊失敗:', error);
});
// 新增 ready()
navigator.serviceWorker.ready.then(registration => {
return registration.pushManager.subscribe({
userVisibleOnly: true,
// 新增 urlBase64ToUint8Array() 解析publickey
applicationServerKey: urlBase64ToUint8Array(publicKey)
});
}).then(subscription => {
console.log('推送訂閱資訊:', JSON.stringify(subscription));
}).catch(error => {
console.error('推送訂閱失敗:', error);
});
}
function 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;
}
// browser 通知權限要開 , os 通知權也要開
document.getElementById('notificationButton').addEventListener('click', function () {
Notification.requestPermission().then(function (permission) {
if (permission === "granted") {
console.log("通知權限已獲得");
// 可以在這裡添加一個新的通知來測試
new Notification("測試通知", { body: "這是一個測試通知" });
} else {
console.log("通知權限被拒絕");
}
});
});
document.getElementById('showNotificationButton').addEventListener('click', function () {
if (Notification.permission === "granted") {
const notification = new Notification("新文章", {
body: "MUKI 發佈了一篇新文章,點我閱讀。"
});
notification.onclick = function () {
window.open("https://muki.tw/ngrok-err-ngrok-6024/", "_blank");
notification.close()
}
}
});
</script>
</body>
</html>