Call Java (Android) methods from Webview using Javascript
-
Create a class named
JSInterface
inside any Activy or other Intent -
Create a class with public methods with
@JavascriptInterface
annotations (Not @JavaS
criptInterface)public class JSInterface { ... @JavascriptInterface public void toastMe(String text) { Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show(); } }
-
Attach the class name as the Webview's JavascriptInterface.
webview.addJavascriptInterface(new JSInterface(this), "JSInterface");
-
Call
JSInterface.toastMe(text)
from Webview's Javascript instancevar text = "I want to be toasted"; JSInterface.toastMe(text);