Android webview - javascript single line comments causing Uncaught SyntaxError errors?

I am trying to load the following html as a string in a webview:

<html> <head> <script> function foo() { // test. } </script> </head> <body> <p>hi.</p> </body> </html> ------------------------------ String content = readAboveContentIntoString(); WebView webview = ...; webview.loadData(content, "text/html", "utf-8"); 

I get the following message from the webview console:

 Uncaught SyntaxError: Unexpected end of input 

If I remove the "// test". comment, I am not getting a syntax error. It’s as if web browsing robs a line of a new line, so the body of the function applies the comment to the closing brace like this:

 function foo() { // test. } 

Can anyone else reproduce this? I thought that maybe my readAboveContentIntoString () removes new lines, but is being tested, but it is not. I am using android 4.4.4.

thanks

- Edit ---

Also, a block comment comment works fine instead of a line comment:

 /* test. */ 
+6
source share
2 answers

I had the same problem. It seems the only way is to first remove the comments from the content line and then upload it to the webview.

 String content = readAboveContentIntoString(); WebView webview = ...; // Add This : content = removeComment(content); webview.loadData(content, "text/html", "utf-8"); 

The removeComment () function removes both single-line comments and block comments.

 private String removeComment(String codeString){ int pointer; int[] pos; String str = codeString; while(true) { pointer = 0; pos = new int[2]; pos[0] = str.indexOf("/*",pointer); pos[1] = str.indexOf("//",pointer); int xPos = xMin(pos); if(xPos != -1){ //========================= Pos 0 if(xPos == pos[0]){ pointer = xPos + 2; int pos2 = str.indexOf("*/", pointer); if(pos2 != -1){ str = str.substring(0,xPos) + str.substring(pos2+2,str.length()); } else{ str = str.substring(0,xPos); break; } } //========================= Pos 1 if(xPos == pos[1]){ pointer = xPos + 2; int pos2 = str.indexOf('\n', pointer); if(pos2 != -1){ str = str.substring(0,xPos) + str.substring(pos2+1,str.length()); } else{ str = str.substring(0,xPos); break; } } } else break; } return str; } private int xMin(int[] x){ int out = -1; for(int i = 0;i < x.length;i++){ if(x[i] > out)out = x[i]; } if(out == -1)return out; for(int i = 0;i < x.length;i++){ if(x[i] != -1 && x[i] < out)out = x[i]; } return out; } 
+2
source

Does your Java line contain a line after the comment line? If not, everything in the javascript element after the first "//" will be interpreted as an incomplete comment on one line, since it does not find "\ n" after "// test".

See comment 5 in this issue: https://issuetracker.google.com/issues/36937564#comment5

0
source

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


All Articles