Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView onPageFinished BUG

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.

like image 854
Marcus J.Kennedy Avatar asked Mar 14 '18 22:03

Marcus J.Kennedy


2 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';");}
like image 52
Speditz Avatar answered Oct 16 '22 17:10

Speditz


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
});
like image 36
anon Avatar answered Oct 16 '22 18:10

anon