Interaction between web and APP -- WebView JavaScript Bridge

In the actual project, we often encounter the situation that the web page is embedded in the app (Hybrid), which requires the interaction between the ...

In the actual project, we often encounter the situation that the web page is embedded in the app (Hybrid), which requires the interaction between the web page and the native app, such as obtaining the current user information. A simple way to do this is through the url parameter, but this way is extremely rigid, so there is jsbridge.
This article aims to record the implementation of WebView JavaScript bridge. If there is any error, please correct it! If you need to understand the jsbridge principle, please google.

Demand:

/** *Function Description: js calls webview event * * jsBridge.callHandler(method, data, callBack(response)); *@ param method method name *@ param data parameter *@ return callback */ /** *Function Description: webView calls JS event * * jsBridge.registerHandler(method, callBack(response)); *@ param method method name *@ return callback */
const JsBridge = { init: function (callback) { const u = navigator.userAgent; const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //Judge mobile system if (!isiOS) { //ios if (window.WebViewJavascriptBridge) { callback(WebViewJavascriptBridge) } else { // Register event, called when WebView JavaScript bridge load is complete document.addEventListener( 'WebViewJavascriptBridgeReady', function () { callback(WebViewJavascriptBridge) }, false ); } } else { //Android // If there is a WebView JavaScript bridge, call back is returned directly if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } // If there are WVJBCallbacks, inject events into WVJBCallbacks if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } // Otherwise, create WVJBCallbacks window.WVJBCallbacks = [callback]; const WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0) } }, first: function () { const u = navigator.userAgent; const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); if (!isiOS) { const _this = this; _this.init(function (bridge) { bridge.init(function (message, responseCallback) { responseCallback(data); }) }) } }, registerHandler: function (name, fun) { const _this = this; _this.init(function (bridge) { bridge.registerHandler(name, fun); }) }, callHandler: function (name, data, fun) { const _this = this; _this.init(function (bridge) { bridge.callHandler(name, data, fun); }) } } // Initialization JsBridge.first();

3 December 2019, 12:07 | Views: 1621

Add new comment

For adding a comment, please log in
or create account

0 comments