Dynamically change HTML element in android webView

I know that this question is very common and can be solved using here - JS or JQuery and here - how to run it on Android. It’s good that these methods work fine, but when we call:

`myWebView.loadUrl("javascript:document.body.innerHTML = document.body.innerHTML.replace('link1', 'link2')");` 

image link1 changes with link2, the image loads, but the page restarts, so if I'm at the end, I'm going to start ... can I just change link1 to link2 in real time so as not to reload the page like in a real browser?

and I also tried setting id in my html file, for example:

 <img src="https://link1.jpg" id="dm5kode"/> 

and run on Android:

myWebView.loadUrl("javascript:document.getElementById('dm5kode').src = 'link2'");

I get nothing here, just a blank screen ...

+5
source share
1 answer

This is not a page reload.

 "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@mail.com "; 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

  <!DOCTYPE html> <html> <head> <title>dynamic Image</title> </head> <body> <img src="https://www.gstatic.com/webp/gallery3/1.png" id="dm5kode"/> </body> </html> 
+9
source

All Articles