Refactor: refactor jsbridge lib makes it easily use

This commit is contained in:
jas0ncn 2018-09-02 16:22:39 +08:00
parent acaee8c63a
commit d64d1786e8

View File

@ -15,7 +15,7 @@
/** /**
* declare javascript bridge API * declare javascript bridge API
*/ */
export interface JsBridge { export interface JsBridgeAPI {
/** /**
* Register a javascript bridge event handle * Register a javascript bridge event handle
@ -41,7 +41,7 @@ declare global {
/** /**
* Global jsbridge instance * Global jsbridge instance
*/ */
WebViewJavascriptBridge?: JsBridge | null WebViewJavascriptBridge?: JsBridgeAPI | null
/** /**
* Global jsbridge init callback * Global jsbridge init callback
@ -53,11 +53,43 @@ declare global {
} }
/** /**
* Check if perched in ClashX Runtime
*/
export function isClashX () {
return navigator.userAgent === 'ClashX Runtime'
}
/**
* Closure save jsbridge instance
*/
export let jsBridge: JsBridge = null
/**
* JsBridge class
*/
export class JsBridge {
instance: JsBridgeAPI = null
constructor (callback = jsbridge => {}) {
if (window.WebViewJavascriptBridge) {
this.instance = window.WebViewJavascriptBridge
callback(this.instance)
}
// init jsbridge
this.initBridge(jsBridge => {
this.instance = jsBridge
callback(jsBridge)
})
}
/**
* setup a jsbridge before app render * setup a jsbridge before app render
* @param {Function} cb callback when jsbridge initialized * @param {Function} cb callback when jsbridge initialized
* @see https://github.com/marcuswestin/WebViewJavascriptBridge * @see https://github.com/marcuswestin/WebViewJavascriptBridge
*/ */
export function setupJsBridge (callback = jsBridge => {}) { private initBridge (callback) {
/** /**
* You need check if inClashX first * You need check if inClashX first
*/ */
@ -81,11 +113,13 @@ export function setupJsBridge (callback = jsBridge => {}) {
WVJBIframe.src = 'https://__bridge_loaded__' WVJBIframe.src = 'https://__bridge_loaded__'
document.documentElement.appendChild(WVJBIframe) document.documentElement.appendChild(WVJBIframe)
setTimeout(() => document.documentElement.removeChild(WVJBIframe), 0) setTimeout(() => document.documentElement.removeChild(WVJBIframe), 0)
}
} }
/** export function setupJsBridge (callback) {
* Check if perched in ClashX Runtime if (jsBridge) {
*/ return callback(jsBridge)
export function isClashX () { }
return navigator.userAgent === 'ClashX Runtime'
jsBridge = new JsBridge(callback)
} }