首先,要注意,使用這個api在background.js
中,不是在content-script
下。然後在content-script
中要通過chrome.runtime.sendMessage 這個api來調起。
在background.js
中要監聽sendMessage
事件:
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
if (request.contentScriptQuery === 'notification') {
const {
options
} = request;
chrome.notifications.create('notify1', options, (id) => {
alert(JSON.stringify(chrome.runtime.lastError)); // 如果沒調成功可以在這裏看看報錯,在生產環境別忘了註釋掉
});
}
console.log('Did not receive the response!!!');
});
然後在你的content-script
中這樣發起:
const options = {
title: 'title',
message: 'message',
type: 'basic',
iconUrl: 'img/icon-16.png',
}
chrome.runtime.sendMessage({
contentScriptQuery: 'notification',
options
});
注意!!
iconUrl
這個字段,必須爲manifest中聲明的圖片文件,如果是網絡圖片可能還要在manifest中設置一下。
還不行看官方文檔 ,搜關鍵字“required”,在“create“時有幾個必填字段,必須都得寫上。還要注意把manifest中的permission中添加”notifications“