简体   繁体   English

在Android WebView中检测HTML按钮单击

[英]Detect html button click in android webview

So in my Android app I open a webview that consists of a form and a button (to submit). 因此,在我的Android应用中,我打开了一个由表单和按钮(提交)组成的Web视图。 The button element looks like this: button元素如下所示:

 <button role="button" class="btn ng-binding" ng-click="actions.collect()" tooltip="default" title="Check form">SAVE</button> 

Everything works except for when I lose internet connection. 一切正常,除非我失去互联网连接。 I am then not able to detect the button click. 然后,我无法检测到按钮单击。 I would in this case like to show an error message saying the user is offline if button is clicked. 在这种情况下,我想显示一条错误消息,说如果单击按钮,则用户处于脱机状态。 How can I do that in my Activity? 如何在我的活动中做到这一点? I'm pretty new to this so please give me more detailed answer if possible. 我对此很陌生,因此,如果可能的话,请给我更详细的答案。

Thanks! 谢谢!

You must work with javascript interface like this: 您必须像这样使用javascript界面​​:

{
...

myWebview.getSettings().setJavaScriptEnabled(true);
myWebview.getSettings().setDomStorageEnabled(true);
myWebview.addJavascriptInterface(new MyJavaScriptInterface(this), "ButtonCheck");

myWebview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        loadMyEvent(clickListener());
    }

    private void loadMyEvent(String javascript){
        myWebview.loadUrl("javascript:"+javascript);
    }

    private String clickListener(){
        return getMyButtons()+ "for(var i = 0; i < buttons.length; i++){\n" +
                "\tbuttons[i].onclick = function(){ console.log('click worked.'); ButtonCheck.boundMethod('button clicked'); };\n" +
                "}";
    }

    private String getMyButtons(){
        return "var buttons = document.getElementsByClassName('your-button-class'); console.log(buttons.length + ' buttons');\n";
    }
});

myWebview.loadUrl("http://....");

...
}


class MyJavaScriptInterface {

    private Context context;

    MyJavaScriptInterface(Context ctx) {
        context = ctx;
    }

    @JavascriptInterface
    public void boundMethod(String html) {
        //Check internet connection
    }

}

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

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