iT邦幫忙

DAY 26
1

Chrome Extension 學習筆記系列 第 26

Chrome Extension 開發實戰篇 26 - 通知訊息

[好讀版]

有了事件頁面的定時更新 Feeds 後,接下來要做通知訊息。當有新的文章是 local storage 沒有的,就發一個通知訊息告知使用者。

建立通知訊息

event_page.js

chrome.notifications.create('newFeed', {
type: 'basic',
iconUrl: chrome.runtime.getURL('icons/icon128.png'),
title: 'New Feed!',
message: ''
}, function (notificationId) {
console.log(notificationId);
});

**說明:**在建立通知訊息時一定要設定 type, iconUrl, title, message 四項參數。另外,type 是通知訊息的種類,有 "basic", "image", "list", or "progress" 四種。
**溫馨小提醒:**要使用通知功能,必須先到 manifest.json 設定檔取得權限。

manifest.json

{
...
"permissions":
[
"notifications",
...
],
...
}

可能會遇到的問題

第一次建立通知訊息時,會正常顯示,但同樣的 notificationId 在建立第二次時,卻不會顯示通知訊息。跟據官網的描述,是會先 clear 再 create,但沒說明會不會再顯示通知訊息。

If it matches an existing notification, this method first clears that notification before proceeding with the create operation.

那筆者的解決方式是自己先 clear 再 create,就可以正常顯示通知訊息,如下所示。

event_page.js

chrome.notifications.clear('newFeed', function (wasCleared) {
chrome.notifications.create('newFeed', {
type: 'basic',
iconUrl: chrome.runtime.getURL('icons/icon128.png'),
title: 'New Feed!',
message: ''
}, function (notificationId) {
console.log(notificationId);
});
});

**說明:**這裡 clear 後,沒有檢查 wasCleared 布林值,因為第一次的情況會是還沒 create 就 clear,所以 wasCleared 為 false。


上一篇
Chrome Extension 開發實戰篇 25 - 儲存 RSS
下一篇
Chrome Extension 開發實戰篇 27 - tts 語音
系列文
Chrome Extension 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言