Javascript Namespaces in Android JavascriptInterface

I am creating a javascript api for my application and I want to use namespaces in my javascript code. However, I cannot get it to work and cannot find any information about the problem.

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 delete .typeOne and have: Android.methodName then it works fine.

+6
source share
2 answers

I am looking at addJavascriptInterface documentation. It says that The Java object fields are not accessible. Since typeOne must be a property of the exported Java object, it seems you will need to organize the "namespace" manually. That is, export TypeOne and put it in a global Android JavaScript object.

So, I assume that you need to create empty objects and add things to them if necessary.

 <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.

+1
source

I think javascript understands that you are calling methodeName on a typeOne object, which is a child of an Android object. But you do not have objects named Android or typeOne. The point in javascript is used for the hierarchy of betweens of parents and child.

You should try to use the name without dots or, call your object in different ways (perhaps the window ["Android.typeOne"]. MethodName ();

0
source

All Articles