WebApp【公共组件库】@前端(For Git Submodule)
Tevin
2021-02-23 58e9066d4eb8acb4cfb49ff7960e1a174153b465
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/**
 * 跨端双向通讯桥
 * @author Tevin
 * @tutorial
 *  网页对 app 发起通讯
 *      1. app 注册接收机制
 *          app 在网页打开之前,注入方法 linking
 *      2. js 发起
 *          bridge.invoking('methodName', {key1:'value1'}, function(res){console.log(res)});
 *      3. Bridge 转换为发送
 *          window.linking('{method:\'methodName\', param:{key1:\'value1\'}, callback:\'bridge.cb111at1541994536008\'}');
 *      4. app 处理完后直接调用网页上的回调,并传递结果
 *          bridge.cb101at1541994536008('{key2:\'value2\'}');
 *  app 对网页发起通讯
 *      1. 网页注册接收器,用于接收 app
 *          window.telling = function(dataStr) {};
 *      2. 网页注册业务
 *          bridge.register('methodName', function(data, callback){});
 *      3. app 调用(至少需要在页面完成再延迟至少1秒之后)
 *          telling('{method:\'methodName\', param:{key1:\'value1\'}, marker:\'mk222at1541994536008\'}');
 *      4. 网页完成业务逻辑处理,并回调
 *          window.linking('{method:\'methodName\', param:{key2:\'value2\'}, marker:\'mk222at1541994536008\'}');
 */
 
 
export class Bridge {
 
    constructor() {
        this._data = {
            count: 100,
        };
        this._receives = {};
        this._init();
    }
 
    /**
     * 检查 linking 方法
     * @return {string}
     * @private
     */
    _checkLinking() {
        // 安卓注入
        if (window.iTop && window.iTop.linking) {
            return 'android';
        }
        // 没有注入
        else {
            return '';
        }
    }
 
    /**
     * 初始化
     * @private
     */
    _init(count = 0) {
        // 500 * 20 毫秒后,仍然未注入,视为不工作
        if (!this._checkLinking() && count < 20) {
            setTimeout(() => {
                this._init(++count);
            }, 500);
        } else {
            this._initReceive();
        }
    }
 
    /**
     * 发送
     * @param {object} data
     * @private
     */
    _send(data) {
        const platform = this._checkLinking();
        // 安卓注入
        if (platform === 'android') {
            window.iTop.linking(JSON.stringify(data));
        }
        // 没有注入
        else {
            console.error('没有注入 linking 方法!');
        }
    }
 
    /**
     * 发起一次发送
     * @param {string} method
     * @param {object} param
     * @param {function} callback - 来自网页业务逻辑的回调
     * @private
     */
    _sendLinking(method, param, callback) {
        // 数据检查
        if (Object.prototype.toString.call(param) !== '[object Object]') {
            console.error('$bridge.invoking 需要接受 JSON 对象!');
            return;
        }
        // 如果有回调,转存回调
        const name = 'cb' + this._data.count++ + 'at' + Date.now();
        this[name] = (res) => {
            if (callback && Object.prototype.toString.call(callback) === '[object Function]') {
                if (res) {
                    const data = typeof res === 'string' ? JSON.parse(res) : res;
                    callback(data);
                } else {
                    callback();
                }
            }
            delete this[name];
        };
        // 发送
        this._send({
            method,
            param,
            callback: 'bridge.' + name,
        });
    }
 
    /**
     * 向 app 发起通讯
     * @param {string} method
     * @param {object|function} [param]
     * @param {function} [callback]
     */
    invoking(method, param, callback) {
        const trans = param;
        if (trans) {
            if (Object.prototype.toString.call(trans) === '[object Function]') {
                callback = trans;
                param = {};
            }
        } else {
            callback = null;
            param = {};
        }
        this._sendLinking(method, param, callback);
    }
 
    /**
     * 初始化接收
     * @private
     */
    _initReceive() {
        if (!this._checkLinking()) {
            return;
        }
        window.telling = (res) => {
            const data = typeof res === 'string' ? JSON.parse(res) : res;
            const method = data.method;
            const param = data.param;
            const marker = data.marker;
            if (this._receives[method]) {
                this._receives[method](param, (param2) => {
                    this._sendTelling(method, param2, marker);
                });
            }
        };
    }
 
    /**
     * 发送响应
     * @param {string} method
     * @param {object} param
     * @param {string} marker
     * @private
     */
    _sendTelling(method, param, marker) {
        // 数据检查
        if (Object.prototype.toString.call(param) !== '[object Object]') {
            console.error('$bridge.register 注册的函数需要接受 JSON 对象!');
            return;
        }
        // 发送
        this._send({
            method,
            param,
            marker,
        });
    }
 
    /**
     * 注册接收指令,可供 app 查询
     * @param method
     * @param callback
     */
    register(method, callback) {
        this._receives[method] = callback;
    }
 
    /**
     * 是否有开始工作
     */
    isWorking() {
        const platform = this._checkLinking();
        return platform === 'android' || platform === 'iOS';
    }
 
}
 
// 全局服务实例
export const $bridge = new Bridge();