Vue.js uni-app mixed mode interaction between native App webview and H5

In modern mobile application development, the interaction between native App and H5 page has become a common requirement. This article will introduce how to implement data transfer and method calls between native App and H5 pages in the Vue.js framework. We'll show how to do this with a simple example. Attached the complete source code download address: https://ext.dcloud.net.cn/plugin?id=13500

The renderings are as follows:
insert image description here

First, we need to introduce a communication bridge between the native App and the H5 page in the Vue.js project. In this example, we'll use a bridge.jsfile named . bridge.jsThe content of the file is as follows:

// #ifdef H5
import Vue from 'vue';
import {
    
     registerHandler } from '@/utils/bridge.js';
Vue.prototype.$bridge = {
    
    
  registerHandler(name, handler) {
    
    
    registerHandler(name, handler);
  },
};
// #endif

Next, we define two methods in the Vue.js component: appToH5()and h5ToApp(). These two methods are respectively used to realize the function of transmitting data from the native App to the H5 page and sending data from the H5 page to the native App.

<template>
  <view class="content">
    <view class="text-area" @click="appToH5()">原生app调用H5方法(原生给H5传值)</view>
    <view class="text-area" @click="h5ToApp()">H5调用原生App方法 (H5给原生传值)</view>
  </view>
</template>

In the object of the Vue.js component methods, we define the concrete implementation of these two methods:

export default {
    
    
  data() {
    
    
    return {
    
    
      title: 'Hello',
      myObjData: {
    
    },
    };
  },
  mounted() {
    
    
    this.appToH5();
  },
  methods: {
    
    
    appToH5() {
    
    
      const handlerName = 'dataToJs'; // 在bridge.js中注册的处理函数名
      const data = JSON.stringify(this.myObjData); // 需要传递的数据,这里以JSON字符串形式表示
      const responseCallback = (responseData) => console.log('H5收到原生数据:', responseData); // H5接收到数据的回调函数

      // 在bridge.js中注册处理函数,并将数据传递给H5页面
      this.$bridge.registerHandler(handlerName, (data, responseCallback) => {
    
    
        if (typeof data === 'string') {
    
    
          const parsedData = JSON.parse(data);
        } else {
    
    
          const parsedData = data;
        }
        responseCallback(parsedData); // 将解析后的数据传递给H5页面的回调函数
      });
    },
    h5ToApp() {
    
    
      const handlerName = 'goLogin'; // 在bridge.js中注册的处理函数名
      const userInfo = 'testUserInfo'; // 需要传递给原生App的用户信息,这里以字符串形式表示
      const responseCallback = (res) => console.log('原生App收到H5数据:', res); // H5接收到数据的回调函数

      // 在bridge.js中调用原生App的方法,并将用户信息传递给原生App
      this.$bridge.callHandler(handlerName, userInfo, responseCallback);
    },
  },
};

In this example, we first methodsdefine appToH5()and h5ToApp()two methods in the object of the Vue.js component. In appToH5()the method, we first obtain the data that needs to be passed to the H5 page, and then bridge.jsregister a processing function in the file, which is responsible for converting the data from a JavaScript object to a JSON string, and passing it to the H5 page. At the same time, we also define a callback function to receive the data returned by the H5 page. Finally, we call this.$bridge.registerHandler()the method register handler function.

Native App implementation, using the WebViewJavascriptBridge framework

1. Introduce the WebViewJavascriptBridge framework

First, we need to introduce the WebViewJavascriptBridge framework into the project. This framework provides a method of bridging iOS and JavaScript, so that we can call JavaScript functions in iOS, and also call iOS methods in JavaScript.

// 引入WebViewJavascriptBridge框架
#import <WebViewJavascriptBridge/WebViewJavascriptBridge.h>

2. Create a bridge object

In the iOS code, we need to create a WKWebViewJavascriptBridge object, which is responsible for managing the communication between JavaScript and iOS.

// js与oc交互
_bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.currentWebView];
// 设置wkwebview代理对象
[_bridge setWebViewDelegate:self];

3. Register native methods for JS calls

Next, we need to register some native methods in the iOS code so that JavaScript can call them. These methods are usually used to handle some special business logic, such as share function and return operation.

// 注册原生方法给JS调用
- (void)registObjcFunction {
    // 注册分享方法
    [self.bridge registerHandler:@"shareClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        [ZJShareManage shareImgWithVC:self title:data[@"title"] describeTitle:data[@"describeTitle"] andUrl:data[@"url"]];
    }];
    
    // 注册返回方法
    [self.bridge registerHandler:@"goNavBack" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

4. Call the JavaScript method

Now that we have registered some native methods, we can call JavaScript methods from iOS code. We just need to use the callHandler:data:responseCallback: method of the _bridge object.

if (self.jsData && self.methodString) {
    [_bridge callHandler:_methodString data:_jsData responseCallback:^(id responseData) {
        DBLog(@"responseData = %@",responseData);
    }];
}

V. Summary

Through the introduction of this article, we learned how to use the WebViewJavascriptBridge framework to interact with JavaScript in iOS. This interactive method is not only easy to use, but also improves development efficiency. I hope this article is helpful to you. If you have any questions or suggestions, please leave a message for discussion.

Guess you like

Origin blog.csdn.net/chenchuang0128/article/details/131827618