Skip to content Skip to sidebar Skip to footer

Accessing Android Api From Browser

I understand I can call android native APIs from javascript if I use an embedded WebView. However, is it possible to access these APIs from a regular browser in Android, such as Fi

Solution 1:

I don't think there is anyway you can call your Android APIs from a regular browser (they do not have them as part of the DOM model), unless you build specific extensions of your own for each browser. That would be tedious work and probably not worth it, since that is exactly why Embedded WebViews exist (like Phonegap).

Now, you can always try do the other way around, which is load your web page from a WebView right from your server. By default, webviews load their content from the local storage of the device, however, using XHR you can call your traditional web pages and show them in the webview.

This can be achieved using either divs that can embed a piece of content from your server or iframes to fully load entire pages from your browser. The second approach will be more transparent since you can fully reuse your current web pages, however it will prevent you from communicating your wrapper with the web page, due to cross origin issues security constraints. I would suggest the first approach, although you probably will have to refactor your server web pages to make them integrate better with your application.

This would work like this (for simplicity in the examples I am using JQuery, but you could do it directly using XHR):

  1. You create a tiny index.html in your webview (phonegap or whatever you are using) and define a that will act as a wrapper to do the calling to your server:

    <html> <head> <!-- Load all your css and javascript stuff here --> </head> <body> <div id="wrapperdiv"></div> </body> </html>

  2. Include a javascript to dynamically load the content from your server:

    $(function() {
        $.ajax({
            url: 'http://www.michaels-server.com/your-web-endpoint',
            type: 'GET',
            crossDomain: true,
            success: function(data, textStatus, xhr) {
                $('#wrapperdiv').html(data);
            }
            error: function() { alert("Cannot contact server."); }
        });
    });
    
  3. Configure your embedded webview to allow cross origin requests. In phonegap you do something like:

    <widget ...> <!-- widget configuration stuff here --> <access origin="*" /> <!-- more widget configuration stuff --> </widget>

The div in your html wrapper will now dynamically load the content from your server. Any javascript in that page can call the Native APIs using the embedded webviews DOM model, such as the one provided by Phonegap.

Hope this helps.

Post a Comment for "Accessing Android Api From Browser"