index.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import cookies from 'js-cookie'
  2. import semver from 'semver'
  3. import { COOKIE_ROOT_DOMAIN, COOKIE_APP_KEY, COOKIE_APP_EXTRA_KEY, COOKIE_ACCESS_TOKEN_KEY, MSG_REQUIRE_LOGIN, APP_INJECT_COOKIE_KEYS, DEF_SYNCED_COOKIE_EXP } from './constant'
  4. import { Notifier, SyncCookiesOptions } from '../types/global'
  5. const setupWebViewJavascriptBridge = (callback) => {
  6. if (window.WebViewJavascriptBridge) {
  7. return callback(window.WebViewJavascriptBridge)
  8. }
  9. if (window.WVJBCallbacks) {
  10. return window.WVJBCallbacks.push(callback)
  11. }
  12. window.WVJBCallbacks = [callback]
  13. var WVJBIframe = document.createElement('iframe')
  14. WVJBIframe.style.display = 'none'
  15. WVJBIframe.src = 'https://__bridge_loaded__'
  16. document.documentElement.appendChild(WVJBIframe)
  17. setTimeout(function () {
  18. document.documentElement.removeChild(WVJBIframe)
  19. }, 0)
  20. }
  21. const parseJWT = (token: string): any => {
  22. const payloadStr = token.split('.')[1]
  23. if (!payloadStr) {
  24. return null
  25. }
  26. try {
  27. return JSON.parse(atob(payloadStr))
  28. } catch (e) {
  29. // tslint:disable-next-line
  30. console.error('[parseJWT]', e)
  31. }
  32. return null
  33. }
  34. const getAppInfo = () => {
  35. const val = cookies.get(COOKIE_APP_KEY)
  36. const matched = val && /^(ios|android)\ ((?:\d\.?)+)$/.exec(val)
  37. if (!matched) {
  38. return null
  39. }
  40. return {
  41. os: matched[1],
  42. version: matched[2]
  43. }
  44. }
  45. const getAppExtra = (): any => {
  46. const val = cookies.get(COOKIE_APP_EXTRA_KEY)
  47. const segments = val && val.split(/\s+/)
  48. if (!segments || !segments.length) {
  49. return {}
  50. }
  51. return segments.reduce((map, item) => {
  52. const matched = /^([0-9a-zA-Z_-]+)\/(.+)$/.exec(item)
  53. if (matched) {
  54. map[matched[1]] = matched[2]
  55. }
  56. return map
  57. }, {})
  58. }
  59. let cachedAppInfo: any
  60. let cachedappExtra: any
  61. class ProginnBridge {
  62. root = window.app_event || window.appBridge
  63. private notifier?: Notifier
  64. constructor(opts?: {
  65. notifier?: Notifier
  66. }) {
  67. const { notifier } = opts || {}
  68. this.notifier = notifier
  69. }
  70. get appInfo() {
  71. cachedAppInfo = cachedAppInfo || getAppInfo()
  72. return cachedAppInfo
  73. }
  74. get appExtra() {
  75. cachedappExtra = cachedappExtra || getAppExtra()
  76. return cachedappExtra
  77. }
  78. get appVersion() {
  79. return this.appInfo?.version
  80. }
  81. get os() {
  82. return this.appInfo?.os
  83. }
  84. get isInApp() {
  85. return !!(this.appInfo || this.root)
  86. }
  87. get isAndroid() {
  88. return /Android/.test(window.navigator.userAgent) || this.os === 'android' || false
  89. }
  90. get isIos() {
  91. return /iP(hone|ad|od)/.test(window.navigator.userAgent) || this.os === 'ios' || false
  92. }
  93. get cookie() {
  94. return cookies.get()
  95. }
  96. get isLogined() {
  97. return !!cookies.get(COOKIE_ACCESS_TOKEN_KEY)
  98. }
  99. get uid(): string | null {
  100. const token = cookies.get(COOKIE_ACCESS_TOKEN_KEY)
  101. const payload = token && parseJWT(token)
  102. return payload?.uid
  103. }
  104. inject(name: string, cb: (...args: any) => void, root = 'Proginn') {
  105. window[root] = window[root] || {}
  106. window[root][name] = cb
  107. }
  108. invoke(fn: string, data: any = null, cb: Function = () => {}) {
  109. if (this.isIos && this.compareAppVersion('gte', '4.22.0')) {
  110. setupWebViewJavascriptBridge((bridge) => {
  111. bridge.callHandler(fn, data, cb)
  112. })
  113. return
  114. }
  115. if (!this.root) {
  116. // tslint:disable-next-line
  117. console.warn(`Bridge invoke ${fn} skipped.`)
  118. return null
  119. }
  120. if (this.isAndroid) {
  121. if (typeof this.root[fn] === 'function') {
  122. return data ? this.root[fn](data) : this.root[fn]()
  123. } else {
  124. return null
  125. }
  126. } else {
  127. return this.root(fn, data)
  128. }
  129. }
  130. back() {
  131. if (!this.isInApp) {
  132. window.history.back()
  133. } else {
  134. if (this.isIos && this.compareAppVersion('gte', '4.22.0')) {
  135. this.invoke('back')
  136. }
  137. else {
  138. this.invoke('back_page')
  139. }
  140. }
  141. }
  142. close() {
  143. if (this.isAndroid || this.compareAppVersion('lt', '4.22.0')) {
  144. this.invoke('finishActivity')
  145. } else {
  146. this.invoke('close')
  147. }
  148. }
  149. load(url: string) {
  150. window.location.href = url
  151. }
  152. open(url: string, title?: string) {
  153. if (this.isInApp && (!this.isAndroid || this.compareAppVersion('gte', '4.20.0'))) {
  154. url = `proginn://webview?url=${encodeURIComponent(url)}${title ? '&title=' + encodeURIComponent(title) : ''}`
  155. }
  156. this.load(url)
  157. }
  158. login() {
  159. if (!this.isInApp) {
  160. return
  161. }
  162. this.load('proginn://login?backToPage=true')
  163. }
  164. checkLogin(force = false) {
  165. if (force || !this.isLogined) {
  166. this.notifier && this.notifier(MSG_REQUIRE_LOGIN, -99)
  167. this.login()
  168. return false
  169. }
  170. return true
  171. }
  172. compareAppVersion(operator: 'gt' | 'lt' | 'gte' | 'lte' | 'eq' | 'neq', version: string) {
  173. return this.appVersion ? semver[operator](this.appVersion, version) : false
  174. }
  175. syncCookies(opts?: SyncCookiesOptions) {
  176. opts = opts || {}
  177. opts.domain = opts.domain || COOKIE_ROOT_DOMAIN
  178. opts.expires = opts.expires || DEF_SYNCED_COOKIE_EXP
  179. for (const key of APP_INJECT_COOKIE_KEYS) {
  180. const val = cookies.get(key)
  181. if (val) {
  182. cookies.set(key, val, opts)
  183. }
  184. }
  185. }
  186. // generally to fix android webview cookies non-inject bug
  187. cacheCookiesInStorage() {
  188. for (const key of APP_INJECT_COOKIE_KEYS) {
  189. const val = cookies.get(key)
  190. if (val) {
  191. window.localStorage.setItem(key, val)
  192. } else {
  193. window.localStorage.removeItem(key)
  194. }
  195. }
  196. }
  197. loadCookiesInStorage(opts?: SyncCookiesOptions) {
  198. opts = opts || {}
  199. opts.domain = opts.domain || COOKIE_ROOT_DOMAIN
  200. opts.expires = opts.expires || DEF_SYNCED_COOKIE_EXP
  201. for (const key of APP_INJECT_COOKIE_KEYS) {
  202. // pass if already exists
  203. if (cookies.get(key)) {
  204. continue
  205. }
  206. const val = window.localStorage.getItem(key)
  207. if (val) {
  208. cookies.set(key, val, opts)
  209. }
  210. }
  211. }
  212. // load data
  213. loadUserData(data: any) {
  214. if (this.isAndroid) {
  215. this.invoke('user_load', data)
  216. }
  217. else if (this.compareAppVersion('lt', '4.22.0')) {
  218. this.invoke('user_load', {
  219. userInfo: data,
  220. })
  221. }
  222. else {
  223. this.invoke('loadUserData', data)
  224. }
  225. }
  226. loadShareData(data: any) {
  227. if (this.isAndroid) {
  228. this.invoke('load_share_data', JSON.stringify(data))
  229. }
  230. else if (this.compareAppVersion('lt', '4.22.0')) {
  231. this.invoke('load_share_data', data)
  232. }
  233. else {
  234. this.invoke('loadShareData', data)
  235. }
  236. }
  237. loadTopicData(data: {
  238. topic_id: string
  239. user_id: string
  240. share_content: any
  241. topics: any[]
  242. }) {
  243. if (this.isAndroid) {
  244. this.invoke('topic_load', data.topic_id)
  245. }
  246. else if (this.compareAppVersion('lt', '4.22.0')) {
  247. this.invoke('topic_load', data)
  248. }
  249. else {
  250. this.invoke('loadTopicData', data)
  251. }
  252. }
  253. // ui
  254. setNavigationBarColor(hex: string) {
  255. if (this.isAndroid || this.compareAppVersion('lt', '4.22.0')) {
  256. this.invoke('setTitleBarColor', hex)
  257. } else {
  258. this.invoke('setNavigationBarColor', hex)
  259. }
  260. }
  261. setNavigationBarTitle(text: string) {
  262. this.invoke('setNavigationBarTitle', text)
  263. }
  264. }
  265. export default ProginnBridge