赞
踩
- 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);
- })
- .catch((err) => {
- if (callback) callback(err, null);
- })
- .finally(() => {
- this.execCallback();
- });
- } else {
- this._scriptList.push(script);
- this._scriptCallbackList.push(callback);
- }
- }
-
- private async execScriptList() {
- if (this._scriptList.length > 0) {
- let count = this._scriptList.length;
- for (let i = 0; i < count; i++) {
- let callback: ScriptCallback = this._scriptCallbackList[i];
- try {
- let result = await this._controller.runJavaScript(this._scriptList[i]);
- if (callback) callback(null, result);
- } catch (err) {
- if (callback) callback(err, null);
- }
- }
- this._scriptList.splice(0, count);
- this._scriptCallbackList.splice(0, count);
- await this.execScriptList();
- }
- }
-
- public setIsReady(value: boolean) {
- this._isReady = value;
- if (this._scriptList.length > 0) {
- this.execScriptList().finally(() => {
- if (this.execCallback) this.execCallback();
- });
- }
- }
-
- public getIsReady(initIsReady: boolean = false, returnValue?: boolean): boolean {
- if (initIsReady) this._isReady = false;
- return returnValue == null ? this._isReady : returnValue;
- }
-
- public resultToInt(result: string, defaultValue: number = 0, radix?: number) {
- if (result && result.length > 0) {
- try {
- return parseInt(result, radix);
- } catch (err) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- public resultToFloat(result: string, defaultValue: number = 0) {
- if (result && result.length > 0) {
- try {
- return parseFloat(result);
- } catch (err) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
- public resultToString(result: string) {
- if (result && result.length > 0) {
- if (result.startsWith('"') && result.endsWith('"')) {
- return result.substring(1, result.length - 1);
- }
- return result;
- }
- return "";
- }
-
- public resultToObject(result: string, defaultValue: Object = null) {
- if (result && result.length > 0) {
- if (result.startsWith('"') && result.endsWith('"')) {
- result = result.substring(1, result.length - 1);
- result = result.replace(/\\\\/gi, '\\');
- result = result.replace(/\\"/gi, '"');
- }
- try {
- return JSON.parse(result);
- } catch (err) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
-
-
- public getJSMethodList(): Array<string> {
- return ["getNumberByField1", "getStringByField1", "getObjectByField1"];
- }
-
- public getNumberByField1(fieldName1: string): number {
- return 88;
- }
-
- public getStringByField1(fieldName1: string): string {
- return "文本";
- }
-
- public getObjectByField1(fieldName1: string): string {
- return JSON.stringify({ key: "值" });
- }
- }
-
- @Builder
- export function JSEngineContainer(jsEngine: JSEngine) {
- if (jsEngine.getIsReady(true, true)) {
- Web({ src: "JSEngine", controller: jsEngine.controller })
- .javaScriptAccess(true)
- .onErrorReceive(() => {
- jsEngine.setIsReady(true);
- })
- .javaScriptProxy({
- object: jsEngine,
- name: "formData",
- methodList: jsEngine.getJSMethodList(),
- controller: jsEngine.controller,
- })
- .width(1)
- .height(1)
- }
- }
-
- @Entry
- @Component
- struct TestAct {
- readonly jsEngine: JSEngine = new JSEngine(() => {
- logDefault("执行完毕")
- });
- @State runResult: string = "";
-
- aboutToAppear() {
- this.jsEngine.runJavaScript("formData.getNumberByField1('field1');", (err, result) => {
- if (err == null) {
- this.runResult = result.toString();
- let temp = this.jsEngine.resultToInt(result);
- logDefault("formData.getNumberByField1('field1') = " + temp);
- }
- });
- }
-
- build() {
- Column() {
- JSEngineContainer(this.jsEngine);
- Button("执行脚本").onClick(() => {
- this.jsEngine.runJavaScript("formData.getStringByField1('field1');", (err, result) => {
- if (err == null) {
- this.runResult = result.toString();
- let temp = this.jsEngine.resultToString(result);
- logDefault("formData.getStringByField1('field1') = " + temp);
- }
- });
- this.jsEngine.runJavaScript("formData.getObjectByField1('field1');", (err, result) => {
- if (err == null) {
- this.runResult = result.toString();
- let temp = this.jsEngine.resultToObject(result);
- logDefault("formData.getObjectByField1('field1') = " + temp["key"]);
- }
- });
- })
- if (this.runResult && this.runResult.length > 0) {
- Text("执行脚本结果:").margin({ top: 16 })
- Text(this.runResult).margin({ top: 16 }).fontColor(Color.Brown)
- }
- }.alignItems(HorizontalAlign.Start).padding(16)
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。