0

I would like to call a dynamic function on a Content Script (Chrome Extension). But the common way doesn't work:

chrome.extension.onRequest.addListener(function cs_listener(request, sender, sendResponse) {
    [request.action]();
}

request.action is blah. Where function blah() is a....and now it comes...a function!

Error thrown:

Error in event handler for 'undefined': TypeError: object is not a function

Someone got over this? I really don't like to make a switch for every action I need.

CYB
  • 421
  • 1
  • 4
  • 12

2 Answers2

1

You have to use

window[request.action]();

as

[request.action]();

creates an array containing request.action, and tries to call that, which results in the error. window[request.action](); gets the property named request.action from window and calls that.

You also might want to check if the property is defined first:

if(typeof window[request.action] == "function")
  window[request.action]();
Digital Plane
  • 37,354
  • 7
  • 57
  • 59
  • Yeah, window[request.action](); works. Strange, i tried it before, but it didn't work. Say hello to the typo. Anyway, thanks! – CYB Aug 22 '11 at 16:51
1

Another way would be just calling that function from a background page, without sending a request:

chrome.tabs.executeScript(null, {code: "dynamic_function_name()"});
serg
  • 109,619
  • 77
  • 317
  • 330
  • This works also, but has a limitation. You may not send a response from the content script to the background script. – CYB Aug 22 '11 at 16:53
  • @Johnny True, you can still send result by initializing a request though. – serg Aug 22 '11 at 17:01