Search code examples
javascriptgoogle-chromegoogle-chrome-extensiongoogle-chrome-app

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


Hi I get an error when calling chrome.notifications.create from inside a function in the js of a chrome app. Can be used fine from outside a function but when within a function I get the following error:

Uncaught TypeError: Cannot read property 'create' of undefined

Here is the code:

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
}

Thanks, I'm a noob when it comes to js and chrome apps so any help is appreciated :)


Solution

  • There are 2 possible causes.

    • You are trying to use this from a content script. You can't: content scripts are very limited in what Chrome APIs they can call.

      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

      In that case, you need to delegate this call to a background script: send a message from the content script, get it in a background script and execute the action.

    • You are trying to call it from an extension script, but did not declare the "notifications" permission.

      In that case the fix is trivial - just add the permission.