Home » Android » java – Android WebView onPageFinished BUG

java – Android WebView onPageFinished BUG

Posted by: admin May 14, 2020 Leave a comment

Questions:

After update API (27) in Android OREO this code is no longer working:

 public void onPageFinished(WebView view, String url) {
     super.onPageFinished(view, url);
     view.loadUrl("javascript:(function() {document.getElementById(\"imPage\").style.display='none';})()");
 }

I have also tried with:

webView.loadUrl(
                    "javascript:(function() { " +

                            "document.addEventListener(\"DOMContentLoaded\", function(event) {" +

                            "document.getElementById(\"imPage\").style.display='none';" +

                            "});" +

                            "})()");

Element not hiding and debug return:

I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot read property 'style' of null", source: mywebsite/ (1)

So I think the javascript is injected before loading page, this explains why the line is 1, because I have other code called after loading page is finished but this code is called when page is white, not loaded.

How to&Answers:

In my own project I have been using evaluateJavascript(script,null) in onPageFinished to hide html elements. view.loadUrl() Should work the same way.

If you don’t need the function be called at later time you could simplify your JS string and instead of \" try using '.

public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:document.getElementById('imPage').style.display='none';");}

Answer:

document.getElementById(\"imPage\") must be returning null.

So there is either no imPageelement or you haven’t loaded the page at the time.

I would suggest moving your entire js code into

document.addEventListener("DOMContentLoaded", function(event) { 
  //insert here
});

Answer:

You have to enable Javascript Seetings like below :-

view.getSettings().setJavaScriptEnabled(true); //Yes you have to do it