javascript 动态更改android webView中的HTML元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32601885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically change HTML element in android webView
提问by johny
I know this question is very common and can be solved using here- JS or JQuery and here- how to run it on Android. Well this methods are working fine but when we call:
我知道这个问题很常见,可以使用这里解决- JS 或 JQuery 和这里- 如何在 Android 上运行它。好吧,这些方法运行良好,但是当我们调用时:
`myWebView.loadUrl("javascript:document.body.innerHTML = document.body.innerHTML.replace('link1', 'link2')");`
image link1 is changing with link2, image is loading but page is restarted, so if I am at the end I am going to the beginning... can I just change link1 to link2 in real time, to not reload the page like in a real browser?
图像链接 1 与链接 2 一起更改,图像正在加载但页面重新启动,所以如果我在最后我要开始...我可以实时将链接 1 更改为链接 2,而不是像在真正的浏览器?
and I tried also setting id in my html file, like:
我还尝试在我的 html 文件中设置 id,例如:
<img src="https://link1.jpg" id="dm5kode"/>
and run on Android:
并在 Android 上运行:
myWebView.loadUrl("javascript:document.getElementById('dm5kode').src = 'link2'");
myWebView.loadUrl("javascript:document.getElementById('dm5kode').src = 'link2'");
here I don't get nothing just empty screen...
在这里,我什么也没有得到,只是空屏幕......
回答by arun
This is not reload the page.
这不是重新加载页面。
"javascript:(
function()
{
document.body.innerHTML = document.body.innerHTML.replace('link1', 'link2')
})()"
example:
例子:
WebView wb;
wb = (WebView) findViewById(R.id.webView1);
wb.loadUrl("file:///android_asset/web1.html");
wb.getSettings().setJavaScriptEnabled(true);
wb.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView web, String url) {
// TODO Auto-generated method stub
String uname = "[email protected]";
String pass = "******";
/*
* web.loadUrl(
* "javascript:(function(){document.getElementById('email').value='"
* + uname +
* "';document.getElementById('pass').value='" +
* pass + "';})()");
*/
String link1 = "https://www.gstatic.com/webp/gallery3/1.png";
String link2 = "https://www.gstatic.com/webp/gallery3/2.png";
web.loadUrl("javascript:(function(){document.body.innerHTML = document.body.innerHTML.replace('" + link1+"', '" + link2+"')})()");
}
});
web1.html
网页1.html
<!DOCTYPE html>
<html>
<head>
<title>dynamic Image</title>
</head>
<body>
<img src="https://www.gstatic.com/webp/gallery3/1.png" id="dm5kode"/>
</body>
</html>