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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With