Nick
Nick

Reputation: 820

Android WebView with local HTML5 + jquery mobile aplication

I'm writing a simple game. I included HTML pages + scrits into the apk file (I put them into assets folder and then loaded into a webview)

browser.loadUrl("file:///android_asset/home.html");

The prototype was only for one player and it was working fine till I needed to add authorization (to have the ability to play with a human:). I created a page for that and did a request:

$.mobile.showPageLoadingMsg();
    $.ajax({
            url: 'https://www.myhost.com/login',
            data: {mail:'[email protected]', password: '123'},
            datatype: 'html',
            type: 'POST',
            success:function(html){
                $.mobile.hidePageLoadingMsg();
                $("#message").html('SUCCESS');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $("#message").html('FAILED');
                $.mobile.hidePageLoadingMsg();
            }
        })

This call works fine. But... then I needed to add account info to all the game pages so the server can know who is doing what. So...I decided t create a bridge for that:

browser.addJavascriptInterface(bridge, "Bridge");

On the Java side I created a function that stores success login info in the Application class (something like a session).

@JavascriptInterface
public void storeAuthData(String callback, String user, String pass) {
WebGameApplication.setUser(user);
WebGameApplication.setPassword(pass);
webview.loadUrl("javascript:"+callback);
}

And it also works. But how can I add this params if I have POST requests? I googled a lot. For GET requests it's possible to do it here:

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    Log.i(TAG, "shouldInterceptRequest: " + url);
    return super.shouldInterceptRequest(view, url);
}

But for POST I'm stuck. Maybe the solution I picked is incorrect? Of course I can extend the bridge by adding one extra method to retrive account info and then include this into each call whether it GET or POST.... but Really? There's no way of doing that?

Thanks in advance.

Upvotes: 0

Views: 676

Answers (1)

ksasq
ksasq

Reputation: 4412

I'm afraid that POST requests are not passed through shouldInterceptRequest, only GET.

Could you set a cookie with the auth data rather than (or in addition to) using a JavaScript Bridge?

FYI, you should update your storeAuthData function such that it posts a task to the WebView, something like this:

@JavascriptInterface
public void storeAuthData(String callback, String user, String pass) {
    ...
    webview.post(new Runnable() {
        @Override
        public void run() {
            webview.loadUrl("javascript:"+callback);
        }
    });
}

The reason for this is important - WebView methods must be run on your applications UI thread, and JavaScript bridge callbacks are executed on a native background thread.

Upvotes: 1

Related Questions