为将由 Android 注入的 JavaScriptInterface 类型添加 TypeScript 定义。然后用Android注入的实例名称声明一个变量,然后照常使用它。在您的示例中,您需要的定义是:
interface JavaScriptInterface {
passParameters(fldMerchCode: string,
fldMerchRefNbr: string,
fldTxnAmt: string,
fldTxnScAmt: string,
fldDatTimeTxn: string,
fldDate1: string,
fldDate2: string) : void;
}
declare var qp: JavaScriptInterface;
The qp
Android注入的实例会有该方法passParameters
可以在上面找到。该实例由 Android 创建,名称为qp
在你的电话中browser.addJavaScriptInterface(javaScriptInterface, "qp");
。请注意,这取决于您的passParameters
使用函数时,您可能需要将返回类型声明为any
代替void
.
这是一个基于以下内容的完整示例Android 绑定 JS 指南 https://developer.android.com/guide/webapps/webview.html#BindingJavaScript:
在您的 HTML 文件中,添加:
<input type="button" value="Say hello" id ="button"/>
<script src="./generated/bundle.js"></script>
我假设您生成/转换的 JavaScript 位于./generated/bundle.js
,相对于 HTML 文件。
在您的 TypeScript 文件中,添加:
interface WebAppInterface {
showToast(toast: string) : any;
}
declare var android: WebAppInterface;
var button = document.getElementById('button');
button.onclick = ()=>android.showToast('Hello Android!');
请注意,链接的 Android 示例命名了注入的对象android
:
webView.addJavascriptInterface(new WebAppInterface(this), "android");
如果链接的示例发生更改或消失,以下是示例 WebAppInterface.java:
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 showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}