Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript namespaces in Android JavascriptInterface

Tags:

android

I am creating a javascript api for my application and I want to use namespaces in my javascript code. However I am unable to get it to work nor find any information on the issue.

Desired Functionality:

HTML:

<script>
    Android.typeOne.methodName();
    Android.typeTwo.methodName();
</script>

Java Code:

webView.addJavascriptInterface(new TypeOneInterface(context), "Android.typeOne");
webView.addJavascriptInterface(new TypeTwoInterface(context), "Android.typeTwo");

However this never works, if I remove .typeOne and have: Android.methodName then that works fine.

like image 935
instigator Avatar asked Feb 24 '14 18:02

instigator


2 Answers

I'm looking at the documentation of addJavascriptInterface. It says that The Java object's fields are not accessible. Since typeOne would have to be a property on the exported Java Object, it seems you would need to arrange the "namespace" by hand. That is, export TypeOne and put it in the global JavaScript Android object.

So I'm guessing you need to create empty objects, and put stuff in them as needed.

<script>
// after stuff has been "injected into the JS context of the main frame"

Android = {};
Android.typeOne = window.TypeOne; 

... and

webView.addJavascriptInterface(new TypeOneInterface(context), "TypeOne");

This answer is a guess, I have never used JavaScript in a WebView.

like image 152
Ярослав Рахматуллин Avatar answered Nov 13 '22 19:11

Ярослав Рахматуллин


I think that javascript understand that you are calling methodeName on object typeOne that is a child of object Android. But you don't have any object named Android nor typeOne. The dot in javascript is used for hierarchy betweens parents and child.

You should try to use name without dots or, call your object differently (perhaps window["Android.typeOne"].methodName();

like image 1
Zoubiock Avatar answered Nov 13 '22 18:11

Zoubiock