2

My Java project based on WebView component. Now, I want to call some JS function with single String argument. To do this, I'm using simple code:

webEngine.executeScript("myFunc('" + str + "');");

*str text is getting from the texarea.

This solution works, but not safe enough. Some times we can get netscape.javascript.JSException: SyntaxError: Unexpected EOF

So, how to handle str to avoid Exception?

Letfar
  • 3,253
  • 6
  • 25
  • 35
  • 1
    possible duplicate of [How to prevent Javascript injection attacks within user-generated HTML](http://stackoverflow.com/questions/942011/how-to-prevent-javascript-injection-attacks-within-user-generated-html) – ergonaut Sep 24 '15 at 20:11

2 Answers2

2

Letfar's answer will work in most cases, but not all, and if you're doing this for security reasons, it's not sufficient. First, backslashes need to be escaped as well. Second, the line.separator property is the server side's EOL, which will only coincidentally be the same as the client side's, and you're already escaping the two possibilities, so the second line isn't necessary.

That all being said, there's no guarantee that some other control or non-ASCII character won't give some browser problems (for example, see the current Chrome nul in a URL bug), and browsers that don't recognize JavaScript (think things like screenreaders and other accessibility tools) might try to interpret HTML special characters as well, so I normally escape [^ -~] and [\'"&<>] (those are regular expression character ranges meaning all characters not between space and tilde inclusive; and backslash, single quote, double quote, ampersand, less than, greater than). Paranoid? A bit, but if str is a user entered string (or is calculated from a user entered string), you need to be a bit paranoid to avoid a security vulnerability.

Of course the real answer is to use some open source package to do the escaping, written by someone who knows security, or to use a framework that does it for you.

blm
  • 2,379
  • 2
  • 20
  • 24
-1

I have found this quick fix:

str = str.replace("'", "\\'");
str = str.replace(System.getProperty("line.separator"), "\\n");
str = str.replace("\n", "\\n");
str = str.replace("\r", "\\n");
Letfar
  • 3,253
  • 6
  • 25
  • 35
  • This definitely isn't "safe". If your title is accurate ("Safe sending String argument to JavaScript function from Java"), this is not a good solution. – DavidS Sep 24 '15 at 20:33