0

I think this is kind of unusual, but this is what I came to. I have a .net application that generates html + js page. I have a thing called Unit that is kind of assembly of different html elements and has artificial events onlaod and onunload.

function DisplayableUnit(content, onload_js, onunload_js)
{
    this.onload_js = onload_js; //different functions calls like "f1(); f2();"
    this.onunload_js = onunload_js;
    this.content = content; //string of html tags
}

function loadUnitTo(elem_id, unit)
{
    var elem = document.getElementById(elem_id);

    if (elem)
        elem.innerHTML = unit.content;

    if (unit.onload_js)
        ;//how to execute it?
}

Many sites says that eval is bad and unsafe thing. But is that the only choice? I need pure JS solution without any third party things.

1
  • 1
    eval is not bad at all, you can't parse a script without it. it's doing stupid crap with eval that's the problem. if your site has no user-generated unmoderated input, then eval is without risk. at any rate, Function() is no better, and in fact, eval() can be made safe in "use strict", but "Function" cannot. Commented Jul 18, 2014 at 18:56

1 Answer 1

2

You can execute it as a function like this:

var theInstructions = "alert('Hello World'); var x = 100",
    F=new Function (theInstructions);

return(F());

Copied from this stackoverflow thread ;)

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Never knew this! Is there any big difference between this and eval other than the fact that this can be called multiple times?
To me it looks like you are just creating a function using the function constructor, so it should be much faster than eval (not sure)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.