Send events from python to javascript using sl4a

I wanted to know the answer to a simple question, but I did not find a good one (I have google for hours :))

I am playing with sl4a with python and I can send events from js to a python script, but js does not capture the eventPost that I injected into the code below from python to js.

Does anyone know how this was done or is there another way without registerCallback?

HTML code:

<html> <head> <script> var droid = new Android(); function doit(){ droid.makeToast("Text send :=>"+document.getElementById("msg").value); droid.eventPost("doit",document.getElementById("msg").value); } function alert_me(data){ droid.makeToast("All done!"); document.getElementById("msg").value = ''; } droid.registerCallback("done",alert_me); </script> </head> <body> <input type="text" name="boton" id="msg" value="" /> <input type="button" name="boton" value="Go!" onclick="javascript:doit()" /> </body> </html> 

PYTHON CODE:

 import android,time if __name__ == '__main__' : droid = android.Android() droid.webViewShow("file:///sdcard/sl4a/scripts/sample.html") while True: event = droid.eventWait().result if event["name"] == 'doit': droid.makeToast("Event catched! %s" % event['data']) droid.eventPost("done","Done message") time.sleep(2) droid.exit() 
+6
source share
2 answers

It is simple to work, but not obvious or well documented.

First you want to get bound to the Android object inside the webview. You can then use it to register one or more callbacks. For a simple example, we just make one message that displays a warning with a message from Python.

  var droid = new Android(); droid.registerCallback("echo", function(msg) { alert(msg.data) }); 

In this case, echo is the name of the type of event with which you want to handle this callback. This way it will handle the β€œecho events”. Event names are arbitrary strings, just name them, which makes sense.

In the Python script that launched the webview, you can now send events to the registered handler whenever you want.

 droid.eventPost("echo", "hello world") 

The second argument here is the message you want to pass to the JavaScript callback.

Note that although you pass the message as a string, it comes into the JavaScript function as an object. This object, which we call msg above, has a data attribute that contains the string that you passed from Python.

+1
source

Unfortunately, I could never get this working using both registerCallback() and eventWaitFor() . However, if you are still interested in getting this work, I highly recommend that you drop by and download sl4a_r5x , an unofficial but newer and updated release of SL4A. It supports the use of FullScreenUi based on the same xml code that is used in Android applications. With this, you can do what you need, and examples can be found on the page. Hope this was helpful and you are still interested in SL4A!

0
source

Source: https://habr.com/ru/post/895637/


All Articles