简体   繁体   English

Android WebView onPageFinished BUG

[英]Android WebView onPageFinished BUG

After update API (27) in Android OREO this code is no longer working: 在Android OREO中更新API(27)后,此代码不再有效:

 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. 所以我认为javascript是在加载页面之前注入的,这解释了为什么行为1,因为我在加载页面完成后调用了其他代码,但是当页面为白色而未加载时调用此代码。

In my own project I have been using evaluateJavascript(script,null) in onPageFinished to hide html elements. 在我自己的项目中,我一直在onPageFinished中使用evaluateJavascript(script,null)来隐藏html元素。 view.loadUrl() Should work the same way. view.loadUrl()应该以相同的方式工作。

If you don't need the function be called at later time you could simplify your JS string and instead of \\" try using ' . 如果您不需要稍后调用该函数,则可以简化JS字符串,而不是\\"尝试使用'

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

document.getElementById(\\"imPage\\") must be returning null . document.getElementById(\\"imPage\\")必须返回null

So there is either no imPage element or you haven't loaded the page at the time. 所以没有imPage元素或者你当时没有加载页面。

I would suggest moving your entire js code into 我建议将整个js代码移入

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

你必须启用如下的Javascript Seetings: -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM