在JavaScript完成之前隐藏WebView

Gro*_*oid 6 javascript android webview

我有一个webview

WebView wv;
wv = (WebView)findViewById(R.id.webView1);
wv.loadUrl("http://example.com/");
Run Code Online (Sandbox Code Playgroud)

简单地说.

在:

onPageFinished
Run Code Online (Sandbox Code Playgroud)

我有:

wv.loadUrl("javascript:(function() { " + "document.getElementsByClassName('centered leaderboard_container')[0].style.display = 'none'; " + "document.getElementsByClassName('n')[0].style.display = 'none'; " + "document.getElementsByClassName('paginator')[0].style.display = 'none'; " + "document.getElementsByTagName('ul')[0].style.display = 'none'; " + "document.getElementsByTagName('tr')[0].style.display = 'none'; " + "})()");
Run Code Online (Sandbox Code Playgroud)

我已将webview可见性设置为INVISIBLE

如何在JavaScript完成后设置对VISIBLE的可见性?

现在你可以看到整个页面,而不是JavaScript完成了..

任何人?

PS.该网站不是我的,它是第三方网站

Ale*_*Bcn 15

在API 17模拟器上测试,它的工作原理.

您可以将Java中的javascript注入Web.

反之亦然,一旦url被加载从javascript调用到我们的Java代码上的函数,并执行setVisibility().为此,您将添加一个JS接口.

这里的代码:

private final static String HOST = "stackoverflow.com";
private WebView wb;

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_home);
    wb = (WebView) findViewById(R.id.home_webview);
    //Make the webview invisible
    wb.setVisibility(View.INVISIBLE);
    WebSettings webSettings = wb.getSettings();
    webSettings.setJavaScriptEnabled(true);
    wb.setWebViewClient(new WebViewClient(){
        public void onPageFinished(WebView view, String url){
            //Inject javascript code to the url given
            //Not display the element
            wb.loadUrl("javascript:(function(){"+"document.getElementById('Id').style.display ='none';"+"})()");
            //Call to a function defined on my myJavaScriptInterface 
            wb.loadUrl("javascript: window.CallToAnAndroidFunction.setVisible()");
        }           
    });

    //Add a JavaScriptInterface, so I can make calls from the web to Java methods
    wb.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
    wb.loadUrl("http://"+HOST);
}

 public class myJavaScriptInterface {
     @JavascriptInterface
     public void setVisible(){
         runOnUiThread(new Runnable() {

            @Override
            public void run() {
                wb.setVisibility(View.VISIBLE);                 
            }
        });
     }

 }
Run Code Online (Sandbox Code Playgroud)

将为每个页面执行此功能.一旦进入第三方服务器,您必须管理如何处理每个请求,webClient.shouldOverrideUrlLoading()可以帮助您.

更新的答案:

我可以像你评论的那样重现它,对于我们应该做的最后一个版本:

从Android 4.2开始,您现在必须使用@JavascriptInterface显式注释公共方法,以便从托管JavaScript中访问它们.请注意,这仅在您将应用的minSdkVersion或targetSdkVersion设置为17或更高时才会生效.

我添加了它并导入 android.webkit.JavascriptInterface

参考:现在必须对WebView中的JavascriptInterface方法进行注释

  • 我仍然看到"整个"页面一秒钟,而JavaScript隐藏了元素.. @AlexBcn (2认同)