Last active
September 5, 2024 08:36
-
-
Save dotNetTree/d779c3aaf49441de40bf8058de0ef8b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare global { | |
interface Window { | |
projectName?: { | |
action: (message: string) => void; | |
}, | |
webkit?: { | |
messageHandlers?: { | |
projectName?: { | |
postMessage?: (message: any) => void | |
} | |
} | |
}, | |
nativeBr?: NativeBr; | |
} | |
} | |
class NativeBr { | |
get isAOS(): boolean { return !!(window.projectName) } | |
private sendMessageToAOS(message: any) { window.projectName!.action(JSON.stringify(message)) } | |
get isIOS(): boolean { return !!(window.webkit?.messageHandlers?.projectName?.postMessage) } | |
private sendMessageToIOS(message: any) { window.webkit!.messageHandlers!.projectName!.postMessage!(message) } | |
private _post: (message: any) => void | |
private _index: number = 0 | |
private cb: any = {} | |
constructor() { | |
this._post = (message) => { | |
if (this.isAOS) { this.sendMessageToAOS(message) } | |
if (this.isIOS) { this.sendMessageToIOS(message) } | |
} | |
} | |
private post<T>(message: any, ms: number = 10 * 1000): Promise<T> { | |
this._index += 1 | |
const key = this._index | |
return new Promise((resolve, reject) => { | |
this.cb[key] = { | |
resolve, | |
reject | |
} | |
setTimeout(() => this._post({ ...message, $cb: `nativeBr._nativecb(${key}, {0}, {1});` }), 15) | |
setTimeout(() => this._nativecb(key, false, { path, message: "TIME_OUT" }), ms) | |
}); | |
} | |
_nativecb(key: number, isFinished: boolean, ret: any) { | |
const cb = this.cb[key] | |
if(cb) { | |
if(isFinished) { | |
cb.resolve(ret) | |
} else { | |
cb.reject(ret) | |
} | |
delete this.cb[key] | |
} | |
} | |
async appVersion(): Promise<NativeBrAppVersionResponse> { | |
let message = { | |
$path: "common/appVersion", | |
$param: { } | |
} | |
return this.post(message, 3 * 1000) | |
} | |
async sum(param: NativeBrSumParam): Promise<NativeBrSumReponse> { | |
let message = { | |
$path: "calculator/sum", | |
$param: param | |
} | |
return this.post(message, 3 * 1000) | |
} | |
} | |
export const nativeBr = new NativeBr() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment