Quantcast
Channel: How to execute a JavaScript function when I have its name as a string - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by SimoAmi for How to execute a JavaScript function when I have its name as a string

$
0
0

People keep saying that eval is dangerous and evil because it can run any arbitrary code. However, if you use eval with a whitelisting approach, assuming you know all the possible function names that may need to be run in advance, then eval is no longer a security concern because the input is no longer arbitrary. Whitelisting is a good and frequent security pattern. Here's an example:

function runDynamicFn(fnName, ...args) {  // can also be fed from a tightly controlled config  const allowedFnNames = ['fn1', 'ns1.ns2.fn3', 'ns4.fn4'];  return allowedFnNames.includes(fnName) ? eval(fnName)(...args) : undefined; }// test function:function fn1(a) {   console.log('fn1 called with', a)}runDynamicFn('alert("got you!")')runDynamicFn('fn1', 'foo')

Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>