Cannot create notification in Chrome Extension. Receive Uncaught TypeError: Cannot read property 'create' of undefined error

Cannot create notification in Chrome Extension. Receive Uncaught TypeError: Cannot read property 'create' of undefined error

我正尝试在收到 HTTP 响应时在我的 Chrome 扩展程序中显示通知。每次尝试时,我都会收到以下错误。

Uncaught TypeError: Cannot read property 'create' of undefined

我已确保我在 manifest.json 中设置了通知权限。

我以为我可以在回调函数中进行通知,但是我为回调传递的任何内容(函数、常量、变量等)始终是未定义的。

这是我的相关代码。

function push(info,tab) {
   function modifyDOM(tab_info, callback) {
    var endpoint = "https://blahblahblah";
    var xmlhttp = new XMLHttpRequest();

    alert(callback); //always undefined. 
  
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4) {
          if (this.status == 200) { 
            alert(this.responseText); 

             var msg = 'Pushed ' + tab_info.tab.url + ' to endpoint'; 
             var opt = {
                 iconUrl: "images/img48.png",
                 type: 'basic',
                 title: 'Handler',
                 message: msg
               };
               chrome.notifications.create(opt); //Error occurs here. 
          }
          else { 
            alert(callback); //always undefined 
          }
      }
    };
  
    xmlhttp.open("POST", endpoint);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.send(JSON.stringify({ "body": {"content": document.body.innerText }, "query": { "url": tab_info.tab.url, "title": tab_info.tab.title} }));
}

chrome.tabs.executeScript({
    code: '(' + modifyDOM + ')(' + JSON.stringify({ "tab" : tab, "callback": 1}) +');' //callback parameter is always undefined in the modifyDOM() function above 
}, (results) => {
    console.log(results[0]);
  });
}

manifest.json

{
 "manifest_version": 2,    
 "version": "1.0",               
 "name": "Handler",   
 "description": "Push to endpoint",
  "icons": {
    "16": "images/img16.png",
    "48": "images/img48.png",
    "128": "images/img128.png"
   },
"permissions": [
    "tabs",
    "contextMenus",
    "*://*/*",
    "notifications"
],
 "background": { 
   "scripts": ["script.js"]
   }
  }

问题 1

函数modifyDOM不在后台脚本中运行。它仅在那里声明,您将其代码转换为字符串并通过 chrome.tabs.executeScript 注入,运行 将代码作为活动选项卡中的内容脚本。内容脚本不能使用大部分 chrome API,它们只能使用少数基本的,如 chrome.i18n、chrome.runtime、chrome.storage.

解决方案是在后台脚本上下文中调用 chrome.notifications,例如从注入的代码发送消息。

问题 2

参数作为单个对象传递{ "tab" : tab, "callback": 1}但函数声明为采用两个。

最简单的解决方案是声明函数也采用单个对象并使用解构

结果

function modifyDOM({tab, callback}) {
  // ..............
  xmlhttp.onload = function () {
    if (this.status == 200) {
      chrome.runtime.sendMessage('Pushed ' + tab_info.tab.url + ' to endpoint');
    }
  };
  // ..............
}

后台脚本全局代码:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  var opt = {
    iconUrl: 'images/img48.png',
    type: 'basic',
    title: 'Handler',
    message,
  };
  chrome.notifications.create(opt); 
});