如何将 javascript 重定向加载到 android webview?

How to load a javascript redirect into android webview?

我正在尝试将页面加载到网络视图中。通常,当我打电话给

webview.loadUrl(url);

它工作正常。 url 有一个重定向页面的 javascript 代码。这是 jacascript 代码:

<script type="text/javascript">
        if (!document.cookie || document.cookie.indexOf('AVPDCAP=') == -1)
        { document.write('<scr'+'ipt src="http://some_link_here+Math.floor(89999999*Math.random()+10000000)+'&millis='+new Date().getTime()+'&referrer='+encodeURIComponent(document.location)+'" type="text/javascript"></scr'+'ipt>'); }
</script>

当我尝试将 javascript 代码加载到我的网络视图中时,如下所示:

String data = javascript_code_above;
topBannerWV.loadDataWithBaseURL("", data, "text/html", "UTF-8", null);

其中数据是此 javascript 代码,它不会加载页面。我还尝试了以下操作:

topBannerWV.loadDataWithBaseURL("", data, "text/javascript", "UTF-8", null);

但是这次文本被加载到 webview 中。谁能帮我解决这个问题?

谢谢。

我正在做这样的事情并且效果很好:

 webView.loadUrl("file:///android_asset/html.html");
webView.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
    try {           
                webView.loadUrl("javascript:init('" + some parameter + "')");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

html 文件中的脚本是:

<script type="text/javascript">
function init(val){
document.getElementById('content').innerHTML=val;
}
window.addEventListener('load',function(){
 console.log("Window Loader");
 init();
});
</script>

我找到了解决方案。

我没有直接将字符串交给webview加载,而是先将其写入文件,然后将该文件交给webview加载。

 getContext().getApplicationContext().deleteFile("data.html");
 Writer output = null;
 File dir = getContext().getApplicationContext().getFilesDir();
 File file = new File(dir.getAbsolutePath() + File.separator + "data.html");
 file.createNewFile();
 output = new BufferedWriter(new FileWriter(file));
 output.write(WVdata);
 output.close();
 topBannerWV.loadUrl("file:///" + getContext().getApplicationContext().getFilesDir() + "/data.html");

我不知道为什么会这样,实际上我没有更改数据字符串,只是将它放入文件中。