1

I am trying to add a little js code into the html of an external webpage using chrome console. I would use iMacros but it has very limited capabilities for my needs.

This is just an example:

document.getElementById('x').innerHTML = 
"<script type='text/javascript'>
alert(\"yes\");
</script>";

When I run it, it says "SyntaxError: Unexpected token ILLEGAL". Is there any workaround or how can I do what I want to do?

2
  • 1
    "HTML5 specifies that a <script> tag inserted via innerHTML should not execute." developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML Commented Feb 1, 2014 at 22:55
  • Thanks. I solved it with document.getElementsByTagName('html')[0].innerHTML and document.write :) Commented Feb 1, 2014 at 22:59

2 Answers 2

1

You can't include line breaks in a string without escaping. Either put it on one line:

document.getElementById('x').innerHTML = "<script type='text/javascript'>alert(\"yes\");</script>";

or escape with a backslash before the newline

document.getElementById('x').innerHTML = 
"<script type='text/javascript'>\
alert(\"yes\");\
</script>";
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It doesn't give any error but still it doesn't alert. I mean the JS code doesn't work after I insert it into the HTML. How can I make it work? I tried setInterval.
@noarm: "HTML5 specifies that a <script> tag inserted via innerHTML should not execute." developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
1

Write your code in single line

document.getElementById('x').innerHTML = 
"<script type='text/javascript'> alert(\"yes\");</script>";

OR

Use \ to make it multi-line variable

document.getElementById('x').innerHTML = 
"<script type='text/javascript'>\
alert(\"yes\");\
</script>";

OR

Use simple string concatenation

document.getElementById('x').innerHTML = 
    "<script type='text/javascript'>" +
    "alert(\"yes\");" +
    "</script>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.