Dynamically recording and evaluating <script>

I want to dynamically write (and evaluate) a script. I am writing in a tag. Why is this code not working?

<html>
<head>

<script id="cojs">

</script>

<script type="text/javascript">
document.getElementById('cojs').innerHTML = 'alert("hey");';
</script>
</head>
<body>
</body>
</html>
+3
source share
2 answers

The characters of the script are evaluated in the analysis. Since the above section is no longer processed after changing it, it does not work.

If your usecase allows it to try the eval function:

<html>
<head>
    <script type="text/javascript">
    eval('alert("hey");');
    </script>
</head>
<body>
</body>
</html>
+1
source

If you want the script to be interpreted, you need to add it to the document. Some browsers do not use innerHTML for scripts, but all will set the script text property.

<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> title</title>

<script>
    window.onload=function(){
        var head=document.getElementsByTagName('head')[0],
        who= document.createElement('script');
        who.text= 'alert("hey");';
        head.appendChild(who);
    }
</script>

</head>
<body>
</body>
</html>
0
source

Source: https://habr.com/ru/post/1790595/


All Articles