Chrome Extension: Content Script -> Dynamic Function
-
08-01-2021 - |
Question
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]();
OTHER TIPS
Another way would be just calling that function from a background page, without sending a request:
chrome.tabs.executeScript(null, {code: "dynamic_function_name()"});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow