Chrome extension: chrome.contextMenus is null

I am developing a Google Chrome extension for myself. It adds an additional menu item to the right-click context menu on each page.

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

Uncaught TypeError: unable to call "create" method from undefined

in the line with the code:

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

So the problem is that chrome.contextMenushere is null . I found out that this may be due to rights , but I have contextmenus permission in my file manifest.json. Here is the permission block in the manifest file:

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

, , , . , ? , , chrome.contextMenus null? ( , btw - -)?

, :

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
}

Javascript. ?

+4
1

chrome.contextMenus undefined script.

Chrome.

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);

, , .

background.js.

+11

Source: https://habr.com/ru/post/1527239/


All Articles