Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically writing and evaluating a <script>

I want to dynamically write (and have evaluated) a script I write to a tag. Why won't this code work?

<html>
<head>

<script id="cojs">

</script>

<script type="text/javascript">
document.getElementById('cojs').innerHTML = 'alert("hey");';
</script>
</head>
<body>
</body>
</html>
like image 801
bgcode Avatar asked Feb 05 '26 02:02

bgcode


1 Answers

Well script tags are evaluated when they are parsed. So since the section above is not parsed anymore after you alter it, it doesn't work.

If your usecase allows it try the eval function:

<html>
<head>
    <script type="text/javascript">
    eval('alert("hey");');
    </script>
</head>
<body>
</body>
</html>
like image 124
Konstantin Weitz Avatar answered Feb 06 '26 15:02

Konstantin Weitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!