Do not use eval(code)
or new Function(code)
as both are basically the same thing and should be blocked by CSP.
Just return your content from the server as content-type: text/javascript
then get it into your page with a <script>
block or import
.
On the server you would have something like (pseudo code, as I don't know what tech stack you're on):
[Route("serverActionReturningCode")]
public string ActionReturningCode()
{
// return the content as JS
Response.Headers.Add("content-type", "text/javascript");
// build the response object as JS
return "window.latestResult = {" +
"a: '" + a + "', " +
"b: '" + b + "', " +
"generatedCode: function() { ... }" +
"};";
}
Then in your page:
<script src="serverActionReturningCode"></script>
<script>
// Now the script above has run and set window.latestResult
console.log('a', window.latestResult.a);
console.log('b', window.latestResult.b);
console.log('function output', window.latestResult.generatedCode());
</script>
This will let you dynamically generate JS functions on the server.
However, if you can avoid the functions and just need to pass values it is a lot simpler to use JSON instead.