是的,有可能。你可以bridge Webview 到你的应用程序 - JS in WebView
你需要做什么:
- 确保在您的 WebView 中启用了 JS
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
- 创建JS监听接口,可以处理WebView发送的消息:
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void openPurchaceModal(String toast) {
//TODO open your purchase screen using mContext as your context
}
}
警告:如果您将 targetSdkVersion 设置为 17 或更高,则必须将 @JavascriptInterface 注释添加到您希望 JavaScript 可用的任何方法,并且该方法必须是公共的。如果您不提供注释,则在 Android 4.2 或更高版本上运行时,您的网页无法访问该方法。
- 设置 WebView 的监听器:
//Adds listener to the webView, under global JS object `Bridge` (You can use any name you want here)
webView.addJavascriptInterface(new WebAppInterface(this), "Bridge");
- 在 WebView 内的 JS 中使用您的
Bridge 对象,无论您需要什么,就像这样:
Bridge.openPurchaceModal();
你可以在你的监听器中定义多个方法,并像这样调用它们:
Bridge.[method name]();
您还可以为这些方法添加原始参数,例如 String、int、boolean 等:
...
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
...
并使用它:
Bridge.showToast("toast text");