我正在尝试将以下 html 作为字符串加载到 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");
我从 webview 控制台收到以下消息:
Uncaught SyntaxError: Unexpected end of input
如果我删除“//测试”。评论,我没有得到语法错误。就好像 webview 正在剥离换行符,所以函数体将注释应用于右括号,如下所示:
function foo() { // test. }
其他人可以复制这个吗?我想也许我的 readAboveContentIntoString() 正在剥离换行符,但经过测试但事实并非如此。我正在使用 android 4.4.4。
谢谢
-- 编辑 ---
此外, block 注释可以很好地代替行注释:
/* test. */
最佳答案
我遇到了同样的问题。似乎唯一的方法是先从内容字符串中删除评论,然后将其加载到 webview。
String content = readAboveContentIntoString();
WebView webview = ...;
// Add This :
content = removeComment(content);
webview.loadData(content, "text/html", "utf-8");
函数 removeComment() 删除单行注释和 block 注释。
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;
}
关于Android webview - 单行 javascript 注释导致未捕获的 SyntaxError 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26495097/