Home > Enterprise >  why the generated function throws out the not defined error
why the generated function throws out the not defined error

Time:09-06

I'm trying to generate a JS script using JS sounds tricky. But the function inside the generated script comes to form and I try to call, it says undefined I'm giving a minimalistic example of my code. I don't know why it's happening maybe function defining on appending or changing the inner html does not work. If you can figure it out that how I can solve this problem, please tell me it'll help out a lot. Thanks! here is the example code.

   <body>
<script>
    
    let b = '<script>function amb(){console.log("hello")}'   '<'   '/'   'script>'

    document.body.innerHTML = b
</script>
<div id="a">
    <button onclick="amb()"> amb</button>
   
</div>
</body>

CodePudding user response:

That is probably because it is not loaded if you just add it afterwards. Nevertheless generating code with code should be avoided! If anywhere input data is used it is that vulnerability. Also it is bad code and hard to understand.

You should overthink your concept and maybe try to explain what you want to achieve and search for in the internet. Or maybe we can here give you a suggestion.

CodePudding user response:

You can't use innerHTML, you will need to append to the body :

var s = document.createElement( 'script' );
s.text = 'alert("test")'
document.body.appendChild( s );

but the real question is why you want to do that

  • Related