How can I create and run a function based on a function name from a string?

1 day ago 4
ARTICLE AD BOX

How can I create and run a function based on a function name from a string?

I need to redo some stuff because we are changing our CSP to block unsafe-inline and unsafe-eval. What I am trying to do right now is bind a function, that I won't know the name of until runtime, to a "click" event.

I am updating TOF/EOF modules the other developers call to build their screens. The original code is over 20 years old. The days of being able to just go with eval(string) are certainly comming to a middle though.

I have a number of these bindings to do and most are fine, but one is frustrating me. The code snippets below should be easily runable. You'll need to feed them a string that is going to parse to an available function, of course.

This is working. The string I start with is "next_page(1)"

/* * Bind prior action click listener */ document.getElementById("priorAction").addEventListener('click',function(){ var cleanString = /(.*)(\()(.*)(\))/; var cleanMatcher = commandString.match(cleanString); fn = cleanMatcher[1] ? cleanMatcher[1] : "console.log"; dn = cleanMatcher[3] ? cleanMatcher[3] : "String for prior action not understood: " + commandString; window[fn](dn); });

This is not working The string I start with is _CF_checkbr([object NodeList])

document.getElementById("submit_link").addEventListener('click',function(){ var cleanString = /(.*)(\()(.*)(\))/; var cleanMatcher = commandString.match(cleanString); fn = cleanMatcher[1] ? cleanMatcher[1] : "console.log"; dn = cleanMatcher[3] ? cleanMatcher[3] : "String for prior action not understood: " + commandString; if(window[fn](dn)) { sendPage(thisForm); } });

I get: webskinFunctions.js:151 Uncaught TypeError: window[fn] is not a function at HTMLImageElement.<anonymous> (webskinFunctions.js:151:18)

The direct call, sendPage(thisForm) works but window['sendPage'](thisForm); does not, it also gives me Uncaught TypeError: window.sendPage is not a function at HTMLImageElement.<anonymous> (webskinFunctions.js:150:35)

I don't understand why it works in one instance, but not the other. new Function(){} is not an option due to the eval-unsafe blocking.

My questions are:

What do I need to look for here? Did I leave information out that is needed to answer this? Since I am trying to defeat a security policy, what should I consider to not create a vulnerability?
Read Entire Article