字符串替换不'当通过android webView JavascriptInterface传递字符串时无法工作

String replace doesn't work when pass string through android webView JavascriptInterface

本文关键字:字符串 JavascriptInterface 工作 webView 替换 android      更新时间:2023-12-14

当我通过JavaScriptInterface将Java字符串传递到android webView时,出现了字符串替换问题。

下面是webView中的HTML(utf-8文件):

 <html>
  <head>
    <script type="text/javascript">
        a=window.MyAndroid.getPicEncStr(); //get string from Java side.        
        function getValue(){    
            b="ue";     
            if(a==b) {
                d="match";
            } else {
                d="not match";
            }
            c=d+":"+a.replace("u","0")+b.replace("u","0");
            document.getElementById("test").innerHTML=c;           
        }
    </script>   
  </head>
  <body>
    <span id="test">test</span>
  </body>
</html>

JavaScriptInterface代码如下:

import java.io.UnsupportedEncodingException;
import android.content.Context;
public class JavaScriptInterface {
    private String unicodeToUtf8(String s) {
        String str=null;
        try {
            str=new String( s.getBytes("utf-8") , "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }
    public String getPicEncStr() {
        //return "ue"; //not work
        return this.unicodeToUtf8("ue"); //not work
    }
}

无论是否从"unicode"转换为"utf-8",当我调用webView.loadUrl("javascript:getValue()")时,span("id"="test")中的结果都是"match:ue0e"。

基本上字符串"a"等于字符串"b",但替换函数不适用于a,只适用于b。

有人能帮我吗?

谢谢。

我似乎找到了解决问题的方法:

<html>
  <head>
    <script type="text/javascript">
        a=window.MyAndroid.getPicEncStr(); //get string from Java side.        
        function getValue(){    
            b="ue";     
            if(a==b) {
                d="match";
            } else {
                d="not match";
            }
            a=new String(a); //<-- force convert java string to javascript string.
            c=d+":"+a.replace("u","0")+b.replace("u","0");
            document.getElementById("test").innerHTML=c;           
        }
    </script>   
  </head>
  <body>
    <span id="test">test</span>
  </body>
</html>

还是不明白为什么。当我转储"a"时,它显示"ue",当我试图转储"a[0]"时,显示"undefined",而"b[0]"是"u,我只能映像Java/Javascript字符串彼此不兼容,因此,需要显式转换。