Trigger chrome.browserAction.onClicked with a function

Viewed 9221

I want to trigger the click, to which following code is listening:

chrome.browserAction.onClicked.addListener(function(tab) {});

The reason is that I have a working extension, which is listening in a background-script (the addListener above) and executes some scripts on click:

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: 'abc.js'});
chrome.tabs.executeScript(tab.id, {file: 'xxx.js'});
});

And now I want to trigger this "onClicked" from a context-menu:

var myContextPage = chrome.contextMenus.create({"title": myTitle, "contexts":["page"],
                                     "onclick": fctContext});

So, I thought, that the easiest way would be to have "click" in fctContext. Maybe there is a better way, but I don't how to solve my problem. I also tried to run "executeScript" but this isn't working neither.

Thanks in advance!

//Update

Solution from answers: This solution is working:

//Shared code. When the argument length is two, it is coming from the context
// menu, while a single argument is coming from the browser action.
function fctContext() {
   var tab = arguments.length == 2 ? arguments[1] : arguments[0];
   // Do whatever you want with the tab.
}

// Browser Action
chrome.browserAction.onClicked.addListener(fctContext);

// Context Menu
chrome.contextMenus.create({
   title: myTitle,
   contexts: ['page'],
   onclick: fctContext
});

Solution after testing some other things:

function fctStart() {
  chrome.tabs.getSelected(null, function(tab){ 
    chrome.tabs.executeScript(tab.id, {file: 'abc.js'});
    chrome.tabs.executeScript(tab.id, {file: 'xxx.js'});
  }); 
}

In this case, fctStart() is working from any point without having to pass the tab.

2 Answers
Related