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
*/
export interface JsBridge {
export interface JsBridgeAPI {
/**
* Register a javascript bridge event handle
@ -41,7 +41,7 @@ declare global {
/**
* Global jsbridge instance
*/
WebViewJavascriptBridge?: JsBridge | null
WebViewJavascriptBridge?: JsBridgeAPI | null
/**
* Global jsbridge init callback
@ -52,40 +52,74 @@ declare global {
}
/**
* setup a jsbridge before app render
* @param {Function} cb callback when jsbridge initialized
* @see https://github.com/marcuswestin/WebViewJavascriptBridge
*/
export function setupJsBridge (callback = jsBridge => {}) {
/**
* You need check if inClashX first
*/
if (!isClashX()) {
return callback(null)
}
if (window.WebViewJavascriptBridge) {
return callback(window.WebViewJavascriptBridge)
}
// setup callback
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback)
}
window.WVJBCallbacks = [callback]
const WVJBIframe = document.createElement('iframe')
WVJBIframe.style.display = 'none'
WVJBIframe.src = 'https://__bridge_loaded__'
document.documentElement.appendChild(WVJBIframe)
setTimeout(() => document.documentElement.removeChild(WVJBIframe), 0)
}
/**
* 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
* @param {Function} cb callback when jsbridge initialized
* @see https://github.com/marcuswestin/WebViewJavascriptBridge
*/
private initBridge (callback) {
/**
* You need check if inClashX first
*/
if (!isClashX()) {
return callback(null)
}
if (window.WebViewJavascriptBridge) {
return callback(window.WebViewJavascriptBridge)
}
// setup callback
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback)
}
window.WVJBCallbacks = [callback]
const WVJBIframe = document.createElement('iframe')
WVJBIframe.style.display = 'none'
WVJBIframe.src = 'https://__bridge_loaded__'
document.documentElement.appendChild(WVJBIframe)
setTimeout(() => document.documentElement.removeChild(WVJBIframe), 0)
}
}
export function setupJsBridge (callback) {
if (jsBridge) {
return callback(jsBridge)
}
jsBridge = new JsBridge(callback)
}