利用 Web 来实现 JavaScript 的动态解析,代码如下:
import webview from '@ohos.web.webview';
function logDefault(msg: Object) {
if (msg) console.log("ArkTS" + (msg ? ": " + msg.toString() : "null"));
}
type ScriptCallback = (error: Error, result: string) => void;
type VoidCallback = () => void;
/**
* 请配合 JSEngineContainer 一起使用
*/
export class JSEngine {
private _controller: webview.WebviewController = new webview.WebviewController();
private _isReady: boolean = false;
private _scriptList: string[] = [];
private _scriptCallbackList: ScriptCallback[] = [];
private execCallback: VoidCallback;
/**
* @param execCallback 执行完毕时,回调的方法
*/
constructor(execCallback?: VoidCallback) {
this.execCallback = execCallback;
}
public setExecCallback(execCallback?: VoidCallback) {
this.execCallback = execCallback;
}
get controller(): webview.WebviewController {
return this._controller;
}
public runJavaScript(script: string, callback?: ScriptCallback) {
if (this._scriptList.length == 0 && this._isReady) {
this._controller.runJavaScript(script)
.then((result) => {
if (callback) callback(null, result);
})
.ca