简体   繁体   中英

Remove part of website from webpage Java

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStatus){
        View view = inflater.inflate(R.layout.fwebview, container, false);
        webView = (WebView) view.findViewById(R.id.webView);
        String url = getArguments().getString("link");

        // Enable Javascript
        webView.getSettings().setJavaScriptEnabled(true);

//set the WebViewClient before calling loadUrl
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                webView.loadUrl("javascript:var con = document.getElementByClassName('page-header'); " +
                        "con.parentNode.removeChild(con); ");
            }
        });
        webView.loadUrl(url);
        return view;
    }

I've wrote this code. Which gets the URL from another Fragment. Doesn't matter for this question. I tried various JavaScript code to remove the header from a webpage www.ad.nl but it doesn't seem to work. The class of the header on that page is page-header. Beside that escaping the function like \\"page-header\\" doesn't work.

Can anyone help me fix this issue?

My take on this would be something like

String js = "javascript:"
            + "function () {"
            + "   var element = document.getElementsByClassName('page-header');"
            + "   element[0].parentNode.remove(element[0]);"
            + "} ();";

and then I would probably use the evaluateJavascript if possible to avoid unnecessary page loads like so:

webView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url)
    {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(js, null);
        } else {
            webView.loadUrl(js);
        }
    }

});

Note that this takes care only the first page-header it encounters and will break if missing but the idea should be clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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