H5/js与App的通讯方式小结

9845次浏览

前言

H5/js与App的通讯,我们公司基础框架是封装了Bridgejs,但是是内部项目,不对外开源。说起这个通信,有一个开源的项目,WebViewJavascriptBridge,需要通信的可以看下这个开源的框架:https://github.com/marcuswestin/WebViewJavascriptBridge 但是简单的通信其实没有必要引入这个框架。其实就是拦截和注入2个部分

通讯方式

前端通知客户端:拦截

客户端通知前端:注入

一、前端通知客户端

在H5页面里触发链接跳转,App Webview检测到链接跳转再进行拦截,因此可以通过URL上携带参数来告知App下一步应该做些什么。

例如如下代码:

import React, { Component } from "react";

export default class App extends Component {
    componentDidMount() {
        location.href = "schema://action?msg=haorooms页面加载完毕"; // 通知App
    }
    render() {
        return (
            <div className="app">
                <button type="button" onClick={this.openMask.bind(this)}>点它</button>
            </app>
        );
    }
    openMask() {
        location.href = "schema://mask?toggle=1"; // 通知App
    }
}

以上执行了location.href = "schema://mask?toggle=1"来通知App打开遮罩层

schema:前端和客户端统一定义链接跳转的协议(喜欢怎样定义协议都行)

mask:App需要执行的动作(喜欢怎样定义动作都行)

toggle=1:动作执行参数(自定义参数,用于告知App怎样做)

如果同步触发两个或以上的location.href(下一个location.href接着上一个location.href),App可能只会接收到一个location.href发出的通知,所以需要对下一个location.href使用setTimeout设置通知时间间隔(可使用Async/Await封装优化)

location.href = "schema://toast?msg=haoroomsone";
setTimeout(() => {
    location.href = "schema://toast?msg=haoroomstwo";
    setTimeout(() => {
        location.href = "schema://toast?msg=haoroomsthree";
    }, 100);
}, 100);

二、客户端通知前端

注入一些全局方法,App Webview直接操作全局方法来控制H5页面,使用window.handleFunc = function() {}这样的形式来定义注入的方法。

import React, { Component } from "react";

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [0, 1, 2, 3, 4]
        };
    }
    componentDidMount() {
        window.addNum = this.addNum.bind(this); // 暴露方法给App
    }
    render() {
        return (
            <div className="app">
                <ul>{this.state.list.map(v => <li key={v}>{v}</li>)}</ul>
            </div>;
        );
    }
    addNum(num) {
        this.setState(prevState => ({
            list: prevState.list.concat(num);
        }));
    }
}

以上在组件加载完成后通过window.addNum = this.addNum.bind(this)将指定方法全局暴露到window上,App Webview可直接操作这些方法来控制H5页面。

小结

H5/js与App的最简单的通信,基本是就是如上所述。

Tags: h5app通信

相关文章: