How do I check if the WebView Javascript interface is available?… here is a solution to the problem.
How do I check if the WebView Javascript interface is available?
If a JavaScript interface is available/defined, is there any correct way to check JavaScript in WebView?
The idea is to define a check method in the interface that can be called and simply return a true if available. Isn’t there a suitable “official” way to do this? Because if the interface is not available/undefined, it throws an error.
I’m using Android, that’s why Java code :
webView.addJavascriptInterface(new WebAppinterface(this),"InterfaceName");
@JavascriptInterface
public void isInterfaceAvailabe (){
return true;
}
In Javascript:
function hasJavaScriptInterface () {
if (InterfaceName.isInterfaceAvailable()){
return true;
}
else {
return false;
}
}
Thanks for the answer!
Solution
First you need to check if the InterfaceName
is actually exported, that is, whether it appears as a property of the window
object. You can do this in a number of ways:
if ("InterfaceName" in window) ...
or
if (window. InterfaceName) ...
or
if (typeof window. InterfaceName === "function") ...
Because if you just try to call an undefined property, you get an error: Uncaught TypeError: window. InterfaceName is not a function