Search code examples
google-chrome-extensionrequestdynamic-function

Chrome Extension: Content Script -> Dynamic Function


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.


Solution

  • 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]();