Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if WebView Javascript Interface is available?

is there any proper way to check in JavaScript inside the WebView, if the JavaScript Interface is available/defined?

My Idea was to define a checking method in the interface, that (if available) could be called and simply return a true. Isn't there a proper 'official' way to do that? Because if the interface is not available/undefined, it will throw an error.

I'm using Android, that's why Java code:

webView.addJavascriptInterface(new WebAppinterface(this),"InterfaceName");

@JavascriptInterface
public void isInterfaceAvailabe (){
   return true;
}

And in Javascript:

function hasJavaScriptInterface () {
   if (InterfaceName.isInterfaceAvailable()){
      return true;
   }
   else {
      return false;
   }
}

Thanks for answers!

like image 455
btx Avatar asked Dec 19 '22 20:12

btx


1 Answers

First you need to check whether InterfaceName is actually exported, that is -- does it present as a property on the window object. You can do it several ways:

if ("InterfaceName" in window) ...

or

if (window.InterfaceName) ...

or

if (typeof window.InterfaceName === "function") ...

Because if you just try invoking a non-defined property, you will get an error: Uncaught TypeError: window.InterfaceName is not a function

like image 142
Mikhail Naganov Avatar answered Dec 21 '22 10:12

Mikhail Naganov