在 Android Webview 中,我可以修改网页的 DOM 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2219074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:01:01  来源:igfitidea点击:

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

javascriptandroidtemplateswebview

提问by TIMEX

Suppose I load a 3rd party URL through webview.

假设我通过 webview 加载了一个 3rd 方 URL。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebChromeClient(new MyWebChromeClient());
        webview.loadUrl("http://ebay.com");         
    }

Is it possible for me to inject something into this WebViewto replace the ebay logo with my own?

我可以在这个 WebView 中注入一些东西来用我自己的标志替换 ebay 标志吗?

回答by Carlos Rendon

To expand on CommonsWare's correct answer:

要扩展 CommonsWare 的正确答案:

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

then in WebClient:

然后在 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]").

简而言之,您等待页面加载。然后你 loadUrl("javascript:[your javascript here]")。

回答by CommonsWare

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.

不直接。您可以通过loadUrl(),在当前网页的上下文中调用 Javascript 代码,就像书签所做的那样。但是,您无法从 Java 代码直接访问 DOM。

回答by alphard

WebView webview = new WebView();

//Maybe need to set to enabled javascript?
webView.getSettings().setJavaScriptEnabled(true);

webview.setWebViewClient(new WebClient());

webview.loadUrl("stackoverflow.com");