Error when using chrome.notifications.create "Uncaught TypeError: Cannot read property 'create' of undefined"

Error when using chrome.notifications.create "Uncaught TypeError: Cannot read property 'create' of undefined"

您好,我在 chrome 应用程序的 js 函数中调用 chrome.notifications.create 时出错。可以在函数外部正常使用,但在函数内部时出现以下错误:

Uncaught TypeError: Cannot read property 'create' of undefined

代码如下:

document.addEventListener('DOMContentLoaded', function () {
document.getElementById('submit').addEventListener('click', submit);
});
function submit() {
  var options = {
    type:"basic",
    title:"nameVal",
    message:"msgVal",
    iconUrl:"icon.png",
  };
  //notification options set
  chrome.notifications.create(options,callback);
  //notification set
}
function callback() {
  console.log("Notification succesfull");
  //notification confirmed
}

谢谢,我是 js 和 chrome 应用程序的菜鸟,所以非常感谢您的帮助:)

您是否已将 chrome 通知权限添加到您的 manifest.json?

添加permissions: ["notifications",//other permissions here]

权限处理扩展中加载和未加载的内容,以及您有权访问的内容。

有 2 个可能的原因。

  • 您正在尝试从 content script 使用它。你不能:内容脚本在它们可以调用的 Chrome API 方面非常有限。

    However, content scripts have some limitations. They cannot:

    Use chrome.* APIs, with the exception of:
    extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
    i18n
    runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )
    storage

    在这种情况下,您需要将此调用委托给后台脚本:send a message 从内容脚本中获取它并执行操作。

  • 您正在尝试从扩展脚本调用它,但未声明 [​​=26=] 权限。

    在那种情况下,修复很简单 - 只需添加权限即可。

当我使用 chrome.notifications 时,我有一个未定义问题的案例。

var options = {
            type: "basic",
            title: "Extention Title",
            message: 'Extention Message",
            iconUrl: "images/icon_86.png" // My Case:Error in iconUrl
        };

但是我的 'icon_86.png' 不在图像文件夹中。

解决方法:使用正确的iconUrl就可以了

('icon_86.png',在我的项目根目录下)