Android: Intercept AJAX call from WebView

前端 未结 3 1422
傲寒
傲寒 2020-12-05 11:41

I want a HTML/javascript application, running in a WebView to make AJAX calls that are handled by the Java code.
Idea

3条回答
  •  一个人的身影
    2020-12-05 12:04

    You can use the JavascriptInterface to intercept the AJAX calls along with JQuery methods ajaxStart and ajaxComplete in following way:

    // our JavascriptInterface
    public class AjaxHandler {
    
        private static final String TAG = "AjaxHandler";
        private final Context context;
    
        public AjaxHandler(Context context) {
            this.context = context;
        }
    
        public void ajaxBegin() {
            Log.w(TAG, "AJAX Begin");
            Toast.makeText(context, "AJAX Begin", Toast.LENGTH_SHORT).show();
        }
    
        public void ajaxDone() {
            Log.w(TAG, "AJAX Done");
            Toast.makeText(context, "AJAX Done", Toast.LENGTH_SHORT).show();
        }
    }
    

    And here is how the AjaxHandler is used in Activity:

        public class MainActivity extends Activity {
    
        private static final String TAG = "MainActivity";
    
        private WebView webView;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.main);
    
            // get web view
            webView = (WebView) findViewById(R.id.web); 
    
            // configure web view 
            final WebSettings webSettings = webView.getSettings();
            webSettings.setBuiltInZoomControls(true);
            webSettings.setJavaScriptEnabled(true);
    
            webView.loadUrl("http://foo.com");
    
            // add javascript interface
            webView.addJavascriptInterface(new AjaxHandler(this), "ajaxHandler");
    
            // override onPageFinished method of WebViewClient to handle AJAX calls 
            webView.setWebViewClient(new WebViewClient() {
    
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
    
                        view.loadUrl("javascript:$(document).ajaxStart(function (event, request, settings) { " +
                                "ajaxHandler.ajaxBegin(); " + // Event called when an AJAX call begins
                                "});");
                        view.loadUrl("javascript:$(document).ajaxComplete(function (event, request, settings) { " +
                                "ajaxHandler.ajaxDone(); " + // Event called when an AJAX call ends
                                "});");
    
                });
        }
    }
    

    The main idea is taken from here and presented with some tweaks.
    Although its a little late to submit an answer but hope this helps others as well!

提交回复
热议问题