2

ok, I start with a very simple method:

alert(someText);

"someText" is a variable, which users will pass a value in by a form. Will there a chance that the user pass following text, and inject some code in my Javascript? For example, can the user pass this in this method:

"anotherText"); alert("the nextText"

If so, how can I prevent it from happening? if not, can anyone mention some security concern about javascript?

4 Answers 4

7

No, it doesn't work that way. String values are not substituted where they are used, they are just used as strings. So there is no security problem.

The only time you may have to worry about this is when you use eval:

eval("alert(\" + someText + "\");");

(Yes, I realize this is a contrived example...)

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

Comments

4

Basically, as long as you're not calling "eval" (or some function that does), and you're not injecting Javascript created from users directly in to pages (via the script tag), you shouldn't have anything to worry about.

Comments

2

Once you have a variable inside javascript it won't matter much unless you do an eval or set the innerHTML property of a DOM element with it.

Aside from that, whether there's a potential for injection depends on how you're getting the value from the form to the javascript.

If for example the form is being submitted to the server and the value of the variable is being set by writing the javascript on the server side you could potentially have a problem. Something like this would obviously leave the script open for injection.

var someText = "<?php echo $_POST["someText"]; ?>";

So it's hard to say whether you could have a security issue without knowing how you're getting the value from the form. In my experience the server side code is the cause of most XSS vectors. In terms of javascript you generally just have to watch for eval and innerHTML.

Comments

0

if "someText" is rendered by server, example JSP、velocity, then it is dangerous

eg

<script>
  alert({{someText}})
</script>

then before JavaScript runtime,while HTML parsing,it is dangerous

but if, “sometext” is javascript variable ,@Zifre's answer is right;

beside, except "eval" keyword, new Function(sometext)、 location.href= sometext ...... may invoke some attacks

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.