Parcourir la source

增加测试postmessage到html的页面。实现上传完成后可以给webview推送消息传回url。

jiaxiaoqiang il y a 9 mois
Parent
commit
c56e7da77a

+ 10 - 5
entry/src/main/ets/pages/Index.ets

@@ -11,6 +11,7 @@ const webUrl = "http://10.88.11.200:11000"
 
 class BridgeModel {
   constructor() {
+
   }
 
   // this.controller.registerJavaScriptProxy 这个里面要对应
@@ -54,9 +55,12 @@ struct Index {
     // 这个必须要调用刷新才起作用, 而且只能执行一次
     if (!this.hasRegistered) {
       console.info(TAG, `registerJavaScriptProxy:`);
+
       this.controller.registerJavaScriptProxy(this.bridgeObj, TAG, ["download", "selectFile", "startCamera", "goToDevicePage"])
       this.controller.refresh()
       this.hasRegistered = true
+
+      uploadInstance.controller = this.controller
     }
   }
 
@@ -66,13 +70,14 @@ struct Index {
         // 这个webview调用相机不知道为什么只能执行一次,选择文件的回到还行,但是为了统一写法还是用registerJavaScriptProxy,但是有时候注册的方法也只能执行一次,不知道为什么。
         // Web({ src: $rawfile('doc_old.html'), controller: this.controller })//测试官方文档 这个是好使的
 
+        // Web({
+        //   src: "http://10.88.20.88:3005",
+        //   controller: this.controller
+        // })
         Web({
-          src: "http://10.88.20.88:3005",
+          src: webUrl,
           controller: this.controller
-        })// Web({
-          //   src: webUrl,
-          //   controller: this.controller
-          // })
+        })
           .mixedMode(MixedMode.All)
           .onlineImageAccess(true)
           .javaScriptAccess(true)

+ 76 - 0
entry/src/main/ets/pages/PostMessagePage.ets

@@ -0,0 +1,76 @@
+// xxx.ets
+import web_webview from '@ohos.web.webview';
+import business_error from '@ohos.base';
+
+@Entry
+@Component
+struct WebComponent {
+  controller: web_webview.WebviewController = new web_webview.WebviewController();
+  ports: web_webview.WebMessagePort[] = [];
+  @State sendFromEts: string = 'Send this message from ets to HTML';
+  @State receivedFromHtml: string = 'Display received message send from HTML';
+
+  build() {
+    Column() {
+      // 展示接收到的来自HTML的内容
+      Text(this.receivedFromHtml)
+      // 输入框的内容发送到html
+      TextInput({ placeholder: 'Send this message from ets to HTML' })
+        .onChange((value: string) => {
+          this.sendFromEts = value;
+        })
+
+      Button('initPorts')
+        .onClick(() => {
+          // 1、创建两个消息端口。
+          this.ports = this.controller.createWebMessagePorts();
+        })
+
+      Button('postMessage')
+        .onClick(() => {
+          try {
+
+            // 2、在应用侧的消息端口(如端口1)上注册回调事件。
+            this.ports[1].onMessageEvent((result: web_webview.WebMessage) => {
+              let msg = 'Got msg from HTML:';
+              if (typeof (result) == "string") {
+                console.log("received string message from html5, string is:" + result);
+                msg = msg + result;
+              } else if (typeof (result) == "object") {
+                if (result instanceof ArrayBuffer) {
+                  console.log("received arraybuffer from html5, length is:" + result.byteLength);
+                  msg = msg + "length is " + result.byteLength;
+                } else {
+                  console.log("not support");
+                }
+              } else {
+                console.log("not support");
+              }
+              this.receivedFromHtml = msg;
+            })
+            // 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。
+            this.controller.postMessage('__init_port__', [this.ports[0]], '*');
+          } catch (error) {
+            let e: business_error.BusinessError = error as business_error.BusinessError;
+            console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
+          }
+        })
+
+      // 4、使用应用侧的端口给另一个已经发送到html的端口发送消息。
+      Button('SendDataToHTML')
+        .onClick(() => {
+          try {
+            if (this.ports && this.ports[1]) {
+              this.ports[1].postMessageEvent(this.sendFromEts);
+            } else {
+              console.error(`ports is null, Please initialize first`);
+            }
+          } catch (error) {
+            let e: business_error.BusinessError = error as business_error.BusinessError;
+            console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
+          }
+        })
+      Web({ src: $rawfile('message.html'), controller: this.controller })
+    }
+  }
+}

+ 16 - 0
entry/src/main/ets/utils/UploadUtil.ets

@@ -4,6 +4,7 @@ import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
 import fs from '@ohos.file.fs';
 import { ProgressDialog } from '../components/ProgressDialog';
 import JGRequest, { JGRequestBaseUrl } from './Request';
+import web_webview from '@ohos.web.webview';
 
 const TAG = "openHarmonyBridge upload"
 
@@ -18,6 +19,7 @@ interface BridgeParams {
   apiUrlPath?: string //上传完成后调的接口 不包含baseurl
   method?: string
   stationIP?: string
+  messageKey?: string //web端会进行window.addEventListener('messageKey' 然后把url整体传回去, 为了后续定义传回去对象的json {fullUrl: ''}
 }
 
 // 上传文件后,返回一个图片的url,然后再调用其他接口上传url和一些值, 如果有其他接口需要key,在这里添加,然后在下面赋值就行了
@@ -38,7 +40,10 @@ interface FileDataModel {
 
 class UploadUtil {
   private baseUrl: string = JGRequestBaseUrl
+  private fileUrl: string = "http://10.88.11.201:9000" //上传完成后可以查看的
   private uploadPath: string = "/api/v1/base/upload"
+  controller: web_webview.WebviewController | null = null
+  ports: web_webview.WebMessagePort[] = [];
 
   private constructor() {
   }
@@ -60,6 +65,8 @@ class UploadUtil {
   }
 
   startUpload(uri: string, callBack: () => void) {
+
+
     // console.log(TAG, "token", this.token === this.uploadParams)
     //   开始上传
     try {
@@ -120,6 +127,15 @@ class UploadUtil {
             data: data
           })
         }
+
+        if (this.uploadParams.messageKey) {
+          uploadInstance.ports = uploadInstance.controller!.createWebMessagePorts();
+          uploadInstance.controller!.postMessage(JSON.stringify({
+            fullUrl: this.fileUrl + result.data?.fileUrl ?? "",
+            messageKey: this.uploadParams.messageKey ?? ""
+          }), [uploadInstance.ports[0]], '*');
+        }
+
         callBack()
 
         //上传完成后浏览器可以产看的图片地址  http://10.88.11.201:9000

+ 2 - 1
entry/src/main/resources/base/profile/main_pages.json

@@ -5,6 +5,7 @@
     "pages/SelectFilePage",
     "pages/TestHdcInstallPage",
     "pages/TestDownloadPage",
-    "pages/StationDevicesPage"
+    "pages/StationDevicesPage",
+    "pages/PostMessagePage"
   ]
 }

+ 41 - 0
entry/src/main/resources/rawfile/message.html

@@ -0,0 +1,41 @@
+<!--index.html-->
+<!DOCTYPE html>
+<html>
+<head>
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>WebView Message Port Demo</title>
+</head>
+
+<body>
+<h1>WebView Message Port Demo</h1>
+<div>
+    <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
+    <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
+</div>
+<p class="output">display received message send from ets</p>
+</body>
+<script>
+//xxx.jsvar h5Port;
+var output = document.querySelector('.output');
+var count = 0;
+window.addEventListener('message', function (event) {
+    count = count + 1
+   output.innerHTML = count + "哈哈哈哈哈";
+})
+
+
+// 3. 使用h5Port往ets侧发送消息.
+function PostMsgToEts(data) {
+    if (h5Port) {
+      h5Port.postMessage(data);
+    } else {
+      console.error("h5Port is null, Please initialize first");
+    }
+}
+
+
+
+
+
+</script>
+</html>