admin管理员组

文章数量:1313347

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!

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!

Share Improve this question asked Jan 27, 2016 at 15:44 btxbtx 2,4973 gold badges26 silver badges39 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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

本文标签: javaHow to check if WebView Javascript Interface is availableStack Overflow