In Android Webview, am I able to modify a webpage's DOM?

前端 未结 3 1635
闹比i
闹比i 2020-11-27 12:53

Suppose I load a 3rd party URL through webview.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCont         


        
相关标签:
3条回答
  • 2020-11-27 13:27

    To expand on CommonsWare's correct answer:

    WebView webview = new WebView();
    webview.setWebViewClient(new WebClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl("stackoverflow.com");
    

    then in WebClient:

    public class WebClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    
        @Override
        public void onPageFinished(WebView view, String url) 
        {       
            // Obvious next step is: document.forms[0].submit()
            view.loadUrl("javascript:document.forms[0].q.value='[android]'");       
        }
    }
    

    In a nutshell, you wait for the page to load. Then you loadUrl("javascript:[your javascript here]").

    0 讨论(0)
  • 2020-11-27 13:30

    Not directly. You can invoke Javascript code in the context of the current Web page, via loadUrl(), much like a bookmarklet does. However, you do not have direct access to the DOM from Java code.

    0 讨论(0)
  • 2020-11-27 13:36
    WebView webview = new WebView();
    
    //Maybe need to set to enabled javascript?
    webView.getSettings().setJavaScriptEnabled(true);
    
    webview.setWebViewClient(new WebClient());
    
    webview.loadUrl("stackoverflow.com");
    
    0 讨论(0)
提交回复
热议问题