我正在尝试将网页加载到webview中。通常,当我打电话
webview.loadUrl(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代码加载到我的webview中时,如下所示:
String data = javascript_code_above;
topBannerWV.loadDataWithBaseURL("", data, "text/html", "UTF-8", null);
其中数据是此javascript代码,它不会加载页面。我也尝试过:
topBannerWV.loadDataWithBaseURL("", data, "text/javascript", "UTF-8", null);
但这次将文本加载到webview中。任何人都可以帮我这个吗?
感谢。
答案 0 :(得分:0)
我正在做这样的事情并且它完美地运作:
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>
答案 1 :(得分:0)
我找到了解决方案。
我没有直接将字符串添加到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");
我不知道为什么会发生这种情况,实际上我不会更改数据字符串,只需将其放入文件中即可。