UNPKG

hatom-js

Version:

npm 插件版本 hatom.js

517 lines (485 loc) 16.7 kB
import './lib/WebViewJavascriptBridge.min.js'; import WebApp from "./lib/config/webApp.json"; import PageRouter from "./lib/config/pageRouter.json"; const vueRouter = {}; ["match", "init", "beforeEach", "beforeResolve", "afterEach", "onReady", "onError", "push", "replace", "go", "back", "forward", "getMatchedComponents", "resolve", "addRoutes"].forEach((method) => { vueRouter[method] = (...args) => { } }); function setupWebViewJavascriptBridge (callback) { if (window.WebViewJavascriptBridge) { callback(window.WebViewJavascriptBridge) } else { document.addEventListener("WebViewJavascriptBridgeReady", function () { callback(window.WebViewJavascriptBridge) }, false) } } function getIsMobile () { const p = window.navigator.platform; const isMobile = p.indexOf("Linux arm") > -1 || p.indexOf("iphone") > -1 || p.indexOf("Linux") > -1 || p.indexOf("iPhone") > -1 || p.indexOf("ipad") > -1 || p.indexOf("iPad") > -1 || p.indexOf("MacIntel") > -1; return isMobile } function initDebug () { return { websocket: null, callback: {}, initWebsocket: function () { console.log('in initWebsocket...') try { const { protocol, hostname } = window.location this.websocket = new WebSocket(`${protocol.replace('http', 'ws')}\/\/${hostname}:7001/${getIsMobile() ? 'mobile' : 'pc'}`) this.websocket.onopen = () => { console.log('websocket 连接成功') } this.websocket.onclose = () => { console.log('websocket 断开连接') this.destroyWebsocket() } this.websocket.onerror = (err) => { console.log('websocket Error', err) this.destroyWebsocket() } this.websocket.onmessage = (e) => { try { const message = JSON.parse(e.data) if (message.type === 'debug') { const { funcName, args, res } = message.data if (message.target === 'mobile') { hatom.native(funcName, this.callback[funcName], args) } else { if (res === 'login') { hatom.$hatomQrcode.close() } else if (res === 'logout') { hatom.$hatomQrcode() } if (funcName && this.callback[funcName]) { hatom.$hatomMessage.close() this.callback[funcName](res) } } console.log('收到消息:', message) } } catch (err) { console.log('信息出错:', err) } } } catch (err) { console.log('websocket Error', err) this.destroyWebsocket() } }, destroyWebsocket: function () { console.log('destory websocket...') if (this.websocket) { this.websocket.close() } this.websocket = null } } } export class Hatom { static webApp = WebApp; static pageRouter = PageRouter; constructor(options) { this.isMobile = getIsMobile() if (options && options.router) { this.router = options.router || vueRouter; } if (options && options.webApp) { this.webApp = options.webApp || WebApp; } if (options && options.pageRouter) { this.pageRouter = options.pageRouter || PageRouter; } setupWebViewJavascriptBridge(function (bridge) { bridge.init() }); } setBridge (funcName, callbackFunc) { try { setupWebViewJavascriptBridge(function (bridge) { bridge.registerHandler(funcName, callbackFunc) }) } catch (err) { console.log(err) } } native (funcName, callbackFunc, args = {}) { if (args && typeof args === "object" && Object.prototype.toString.call(args).toLowerCase() === "[object object]" && !args.length) { args = JSON.stringify(args) } else { console.log("args不符合规范") } if (!callbackFunc) return if (getIsMobile()) { window.WebViewJavascriptBridge.callHandler(funcName, args, (res) => { res = JSON.parse(res); const rsp = { funcName: funcName, res: res, status: res.code === 0 ? "success" : "fail" } if (this.debug && this.debug.websocket && this.debug.websocket.readyState === 1) { this.debug.websocket.send(JSON.stringify({ res: res, funcName: funcName, status: res.code === 0 ? "success" : "fail" })) } return callbackFunc(res) }) } else { if (this.debug && this.debug.websocket && this.debug.websocket.readyState === 1) { this.debug.websocket.send(JSON.stringify({ funcName: funcName, args: JSON.parse(args) })) hatom.$hatomMessage(`正在调用${funcName}`) } console.log("调用插件:", funcName) } } camera (callbackFunc, args = {}) { this.native("CameraLauncher.takePicture", callbackFunc, args) } networkManager (callbackFunc) { this.native("NetworkManagerPlugin.registerNetWorkReceiver", callbackFunc) } phoneCall (callbackFunc, args = {}) { this.native("System.phoneCall", callbackFunc, args) } sharePic (callbackFunc, args = {}) { console.log("sharePic ..."); this.native("System.sharePic", callbackFunc, args) } shareText (callbackFunc, args = {}) { console.log("shareText ..."); this.native("System.shareText", callbackFunc, args) } goMapApp (callbackFunc, params) { this.native("GetMapAppPlugin.getMapApp", callbackFunc, params) } scan (callbackFunc) { this.native("BarcodeScannerPlugin.scan", callbackFunc) } router = { push: (route) => { // 判断当前的路由格式 if (Object.prototype.toString.call(route) === "[object Object]" && route.path) { const routes = this.pageRouter.routes; if (routes.some((page) => page.name === route.path)) { getIsMobile() ? this.native("Router.pushPage", (res) => { console.log("Router.pushPage调用成功:", res) }, { params: { page: `${route.path}.html` }, target: `html:${this.webApp.h5packCode}:\/\/${route.path}.html` }) : window.location.href = `${route.path}.html` } else { hatom.vueRouter.push(route) } } else { console.log("参数有误:", route) } }, pop: (route) => { if (Object.prototype.toString.call(route) === "[object Object]" && route.path) { const routes = this.pageRouter.routes; if (routes.some((page) => page.name === route.path)) { getIsMobile() ? this.native("Router.popPage", (res) => { console.log("Router.popPage调用成功:", res) }, { params: { page: `${route.path}.html` }, target: `html:${this.webApp.h5packCode}:\/\/${route.path}.html` }) : window.history.back() } else { hatom.vueRouter.back() } } else { getIsMobile() ? this.native("Router.popPage", (res) => { console.log("Router.popPage调用成功:", res) }) : hatom.vueRouter.back() } } } locationInfo = { getLocation: (callbackFunc, args={}) => { this.native(`GetLocationInfoPlugin.getLocation`, callbackFunc, args) }, getLocationPermission: (callbackFunc, args={}) => { this.native(`GetLocationInfoPlugin.getLocationPermission`, callbackFunc, args) }, turnOffLocation: (callbackFunc, args={}) => { this.native(`GetLocationInfoPlugin.turnOffLocation`, callbackFunc, args) } } singleRealPlay = { realPlay: (callbackFunc, params)=>{ this.native(`SingleRealPlay.realPlay`, callbackFunc, params) }, playBack: (callbackFunc, params)=>{ this.native(`SingleRealPlay.playBack`, callbackFunc, params) }, } rootInfo = { getRootInfo: (callbackFunc, args={}) => { this.native(`GetRootInfoPlugin.getRootInfo`, callbackFunc, args) }, redirectLogin: (callbackFunc, args={}) => { this.native(`GetRootInfoPlugin.redirectLogin`, callbackFunc, args) }, } setting = { updateApp: (callbackFunc, args={})=>{ this.native(`SettingPlugin.redirectLogin`, callbackFunc, args) }, logout: (callbackFunc, args={})=>{ this.native(`SettingPlugin.logout`, callbackFunc, args) }, modifyPassword: (callbackFunc, args={})=>{ this.native(`SettingPlugin.modifyPassword`, callbackFunc, args) }, gotoSetting: (callbackFunc, args={})=>{ this.native(`SettingPlugin.gotoSetting`, callbackFunc, args) }, gestureSetting: (callbackFunc, args={})=>{ this.native(`SettingPlugin.gestureSetting`, callbackFunc, args) }, messageSetting: (callbackFunc, args={})=>{ this.native(`SettingPlugin.messageSetting`, callbackFunc, args) }, cameraFaceRecognition: (callbackFunc, args={})=>{ this.native(`SettingPlugin.cameraFaceRecognition`, callbackFunc, args) }, getStatusInfo: (callbackFunc, args={})=>{ this.native(`SettingPlugin.getStatusInfo`, callbackFunc, args) } } page = { preload: (callbackFunc, params={}) => { this.native("Router.preload", callbackFunc, params) }, exit: (callbackFunc, args={}) => { this.native("Router.exitWebApp", callbackFunc, args) }, popPage: (route) => { if (getIsMobile()) { this.native("Router.popPage", (res) => { console.log("调用Router.openPage成功") }, route) } else { console.log("调用Router.pushPage"); if (route) { window.location.hash = ""; window.location.pathname = route.params.page } else { window.history.back() } } }, pushPage: (route) => { if (getIsMobile()) { this.native("Router.pushPage", (res) => { console.log("调用Router.openPage成功") }, route) } else { window.location.hash = ""; window.location.pathname = route.params.page } }, back: (callbackFunc=()=>({}), params={}) => { if (getIsMobile()) { this.native("Router.backHistory", callbackFunc, params) } else { window.history.back() } }, cleanCache: (callbackFunc, args={}) => { this.native("Router.clearCache", callbackFunc, args) } } message = { startMessage: (callbackFunc, params={}) => { this.native(`PushMessagePlugin.startMessagePush`, callbackFunc, params) }, stopMessage: (callbackFunc, params={}) => { this.native(`PushMessagePlugin.stopMessagePush`, callbackFunc, params) } } topBar = { setTopBarLeftButton: (callbackFunc, params={}) => { this.native(`topbar.setTopBarLeftButton`, callbackFunc, params) }, setTopBarLeftButton: (callbackFunc, params={}) => { this.native(`topbar.setTopBarLeftButton`, callbackFunc, params) }, setTopBarTitle: (callbackFunc, params={}) => { this.native(`topbar.setTopBarTitle`, callbackFunc, params) }, setTopBarBackground: (callbackFunc, params={}) => { this.native(`topbar.setTopBarBackground`, callbackFunc, params) }, } bottomBar = { setItemConfig: (callbackFunc, params) => { this.native(`bottomNavigation.setItemConfig`, callbackFunc, params) }, selectItem: (callbackFunc, params) => { this.native(`bottomNavigation.selectItem`, callbackFunc, params) }, setBadge: (callbackFunc, params) => { this.native(`bottomNavigation.setBadge`, callbackFunc, params) } } storage = { setItem: (key, value) => { if (getIsMobile()) { const obj = {}; obj[key] = value; this.native("DataSharePlugin.saveData", (res) => { console.log(key, value) }, obj) } else { window.localStorage.setItem(key, value) } }, getItem: (key, callbackFunc) => { if (getIsMobile()) { const obj = {}; obj[key] = key; this.native("DataSharePlugin.getData", callbackFunc, obj) } else { const res = window.localStorage.getItem(key); callbackFunc(res) } } } getScreenInfo = (callbackFunc, args={}) => { this.native("Device.getScreenInfo", callbackFunc, args) } getSyncScreenInfo = async (args={}) => new Promise((resolve) => { this.native("Device.getScreenInfo", async (res) => { resolve(res) }, args) }) deviceScreenInfo = { getScreenInfo: (callbackFunc, args={}) => { this.native("Device.getScreenInfo", callbackFunc, args) }, getSyncScreenInfo: async (args={}) => new Promise((resolve) => { this.native("Device.getScreenInfo", async (res) => { if (res.code === "0") { const screenInfo = JSON.parse(res.message); resolve(screenInfo) } else { resolve({}) } }, args) }), getStatusBarHeight: async (args={}) => { const res = await this.getSyncScreenInfo(args); if (res.code === "0") { const screenInfo = JSON.parse(res.message); return screenInfo.statusBarHeight / screenInfo.screenDensity } else { return 0 } }, getScreenWidth: async (args={}) => { const res = await this.getSyncScreenInfo(args); if (res.code === "0") { const screenInfo = JSON.parse(res.message); return screenInfo.getScreenWidth } else { return 0 } }, getScreenScreenRotation: async (args={}) => { const res = await this.getSyncScreenInfo(args); if (res.code === "0") { const screenInfo = JSON.parse(res.message); return screenInfo.screenScreenRotation } else { return 0 } }, getScreenHeight: async (args={}) => { const res = await this.getSyncScreenInfo(args); if (res.code === "0") { const screenInfo = JSON.parse(res.message); return screenInfo.screenHeight } else { return 0 } } } deviceInfo = { getScreenInfo: (callbackFunc, args={}) => { this.native("Device.getScreenInfo", callbackFunc, args) }, getNetInfo: (callbackFunc, args={}) => { this.native("Device.getNetInfo", callbackFunc, args) }, getDeviceInfo: (callbackFunc, args={}) => { this.native("Device.getDeviceInfo", callbackFunc, args) } } appInfo = { getAppInfo: (callbackFunc, args={}) => { this.native("AppInfo.getAppInfo", callbackFunc, args) } } notify = { setNotify: (callbackFunc, params={}) => { this.native("NotifyPlugin.notify", callbackFunc, params) } } statusBar = { setStatusBarMode: (data={}, callbackFunc) => { this.native("StatusBar.setStatusBarMode", callbackFunc, data) } } coreServer = { token: (callbackFunc, params) => { this.native("CoreServerPlugin.token", callbackFunc, params) }, queryService: (callbackFunc, params) => { this.native("CoreServerPlugin.queryService", callbackFunc, params) }, getAccountInfo: (callbackFunc, params) => { this.native("CoreServerPlugin.getAccountInfo", callbackFunc, params) } } linkMapInfo = { resIndexCodes: (callbackFunc, params) => { this.native("LinkMapInfoPlugin.resIndexCodes", callbackFunc, params) } } } export const hatom = new Hatom(); export function install (Vue, opts={}) { hatom.vueRouter = opts.router || vueRouter; if (process.env.DEBUG && opts.HatomMessage && opts.HatomQrcode) { hatom.$hatomMessage = opts.HatomMessage hatom.$hatomQrcode = opts.HatomQrcode hatom.debug = initDebug() hatom.debug.initWebsocket() hatom.setBridge('onDestroyView', () => { if (hatom.debug && hatom.debug.websocket && hatom.debug.websocket.readyState === 1) { hatom.debug.destroyWebsocket() } }) if (!getIsMobile()) { hatom.$hatomQrcode() } } Vue.prototype.$hatom = hatom }; export const hatomInstall = install;