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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With