Messages between HtmlPage and AndroidApp using GeckoView

437 views Asked by At

Unfortunetly, I using a platform where WebView is not available, so, I can't make use of the simplicity of JavascriptInterface to interact from my webpage with my app.

Is there a complete (straight forward) example out there explaining how to Interact a page with my Android app using Geckoview?

I tried steps on this page (and others):

https://firefox-source-docs.mozilla.org/mobile/android/geckoview/consumer/web-extensions.html

Frankly speaking, I never saw a page hiding so many details like that.

Html page as simple as this, hosted (lets say) in "http://example.com/x.html":

<html>
<script>
   function appToPage(s)
   {
      log('received:' + s);
   }

   function pageToApp(s)
   {
      // do something to send s to app
      log('sent:' + s);
   }

   function log(s)
   {
      var x = document.getElementById('x');
      x.innerHTML += '<br>' + s;
   }
   
   var i = 0;
</script>

<body>
<input type=button onclick="pageToApp('helloFromPage' + (i++))" value="SEND">
<div id="x"></div>
</body>
</html>

<script>
   log('started');
</script>

Android side:

public class MainActivity extends AppCompatActivity
{
   protected void onCreate(Bundle savedInstanceState)
   {
      ...
      //all the stuff needed for GeckoView and extensions
      geckoSession.loadUri("http://example.com/x.html");
      ...
   }


   // when some user press some button in the browser
   public void onSendButtonClick()
   {
      // do somenthing to call appToPage("helloFromApp");
   }

   // this should be called when a message arrives
   public void onMessageFromPage(String s)  // or whatever object as parameter (JSON, for example)
   {
      Log.d("msgFromPage", s)
   }
   ...
}      
1

There are 1 answers

0
Peeyussh Yadav On

I'm also using Geckoview from a month ago. To interact with your Website content you have to use a web extension. There are two methods:

  1. messaging
  2. port messaging

I'm sharing an example link: https://searchfox.org/mozilla-central/source/mobile/android/examples