解決chrome擴展發通知不顯示的問題

首先,要注意,使用這個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“

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章