8

I am developing a Google Chrome extension for myself. It adds an extra menu item to the right click context menus of the images on every page.

Currently, my extension works without a problem, but when I check console logs, I see this error log:

Uncaught TypeError: Cannot call method 'create' of undefined

on the line with code:

var id = chrome.contextMenus.create({
        "title": title, "contexts": [context],
        "onclick": genericOnClick
    });

So the problem is, chrome.contextMenus comes null here. I found out that it might be related to the permissions, but I have contextmenus permission in my manifest.json file. Here's the permissions block in manifest file:

  "permissions": [
    "contextMenus",
    "notifications",
    "<all_urls>"
  ],

And besides all that, my extension works as it should be. So why am I seeing this error on the log? Should I simple add a null check to do nothing if chrome.contextMenus is null? Or should I wait for it to be initialized (I have no idea how to do that btw -without using an old style while loop-)?

Here's the block of code that causes this error:

var contexts = ["image"];
for (var i = 0; i < contexts.length; i++) {
    var context = contexts[i];
    var title = "Do something";

    var id = chrome.contextMenus.create({
        "title": title, "contexts": [context],
        "onclick": genericOnClick
    });
}

function genericOnClick(info, tab) {
    // some stuff
}

I am not very familiar with Javascript. How can I fix that problem?

Thanks in advance

Utku Özdemir
  • 7,390
  • 2
  • 52
  • 49

1 Answers1

21

chrome.contextMenus is undefined in the content script.

You can check this using Chrome console.

You need create context menu item in background.js script:

content.js

        var requestData = {"action": "createContextMenuItem"};
        //send request to background script
        chrome.extension.sendRequest(requestData);

background.js:

function onRequest(request, sender, callback){    
   if(request.action == 'createContextMenuItem'){
           var contextItemProperties = {};
           contextItemProperties.title = 'context menu item';
           chrome.contextMenus.create(contextItemProperties);
   }
} 

//subscribe on request from content.js:
chrome.extension.onRequest.addListener(onRequest);

I am surprised why the documentation does not mention that you can create context menu item only in background page.

Also you need reload extension after you change the code in background.js.

E Ciotti
  • 4,740
  • 1
  • 25
  • 17
Dmytro Kutetskyi
  • 701
  • 6
  • 11
  • 6
    Update: sendRequest and onRequest are now obsolete. You should use sendMessage and onMessage. See [here](https://developer.chrome.com/extensions/messaging) – Peter Aug 27 '15 at 17:12