|
@@ -1,78 +0,0 @@
|
|
|
-class Bridge extends EventTarget {
|
|
|
- #analysis(string) {
|
|
|
- let data = { type: '', payload: null, callbackId: '' };
|
|
|
- try {
|
|
|
- data = JSON.parse(string);
|
|
|
- } catch (e) {
|
|
|
- console.log('log:bridge:js', `[analysis] 解析消息错误: ${e.message}`);
|
|
|
- }
|
|
|
- if (
|
|
|
- data.payload
|
|
|
- && typeof data.payload === 'object'
|
|
|
- && data.payload['__code__'] != null
|
|
|
- && data.payload['__message__'] != null
|
|
|
- ) {
|
|
|
- data.error = { code: data.payload['__code__'], message: data.payload['__message__'] };
|
|
|
- }
|
|
|
- return data;
|
|
|
- }
|
|
|
-
|
|
|
- #pool = new Map();
|
|
|
-
|
|
|
- static getInstance() {
|
|
|
- return Bridge._instance ?? (Bridge._instance = new Bridge());
|
|
|
- }
|
|
|
-
|
|
|
- static get Platform() {
|
|
|
- return window['AndroidBridge'];
|
|
|
- }
|
|
|
-
|
|
|
- static get UUID() {
|
|
|
- return crypto.randomUUID();
|
|
|
- }
|
|
|
-
|
|
|
- static pulse(userId) {
|
|
|
- const { promise, ...resolvers } = Promise.withResolvers();
|
|
|
- this.getInstance().#postMessage('pulse', { userId }, resolvers);
|
|
|
- return promise;
|
|
|
- }
|
|
|
-
|
|
|
- static print(payload) {
|
|
|
- const { promise, ...resolvers } = Promise.withResolvers();
|
|
|
- this.getInstance().#postMessage('print', payload, resolvers);
|
|
|
- return promise;
|
|
|
- }
|
|
|
-
|
|
|
- dispatch(message) {
|
|
|
- console.log('log:bridge:js', `[dispatch] 接收到消息: ${message}`);
|
|
|
- const { type, callbackId, payload, error } = this.#analysis(message);
|
|
|
- if (callbackId) {
|
|
|
- const { resolve, reject } = this.#pool.get(callbackId) ?? {};
|
|
|
- if (error) { reject?.(error); } else { resolve?.(payload); }
|
|
|
- this.#pool.delete(callbackId);
|
|
|
- } else {
|
|
|
- let event;
|
|
|
- if (error) event = new ErrorEvent(type, { error, message: error.message });
|
|
|
- else event = new CustomEvent(type, { detail: payload });
|
|
|
- super.dispatchEvent(event);
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- addEventListener(type, callback, options) {
|
|
|
- super.addEventListener(type, callback, options);
|
|
|
- return () => super.removeEventListener(type, callback);
|
|
|
- }
|
|
|
-
|
|
|
- #postMessage(type, payload, resolvers) {
|
|
|
- const callbackId = `${type}:${Bridge.UUID}`;
|
|
|
- this.#pool.set(callbackId, resolvers);
|
|
|
- const message = JSON.stringify({ type, payload, callbackId })
|
|
|
- Bridge.Platform.postMessage(message);
|
|
|
- console.log('log:bridge:js', `[post] 发送的消息: ${message}`);
|
|
|
- }
|
|
|
-}
|
|
|
-
|
|
|
-window['Bridge'] = Bridge;
|
|
|
-window['bridge'] = Bridge.getInstance();
|
|
|
-
|
|
|
-window.print = Bridge.print.bind(Bridge);
|