H5在WebView上開發小結

janto007發表於2019-02-28

背景

來自我司業務方要求,需開發一款APP。但由於時間限制,只能採取套殼app方式,即原生app內嵌webview展示前端頁面。本文主要記述JavaScript與原生app間通訊,以及內嵌webview開發時,前端方面可能踩的一些坑。

技術架構

前端:vue+vuex+vue-router+webpack全家桶開發
後端:Node(express框架)簡單轉發介面至java-真後端介面。

js與原生通訊

採用jsBridge技術和原生APP通訊
android 傳送門 和ios 傳送門,因為兩個平臺初始化方式不同,因此在開發過程中,需針對每個平臺做對應操作。 具體做法

  1. 按照庫要求,宣告好初始化函式
//android
function connectWebViewJavascriptBridge{
    if (window.WebViewJavascriptBridge) {
            //do your work here
        } else {
            document.addEventListener(
                'WebViewJavascriptBridgeReady'
                , function() {
                    //do your work here
                },
                false
            );
        }
}
//ios
setupWebViewJavascriptBridge(function(bridge) {
	
	/* Initialize your app here */

	bridge.registerHandler('JS Echo', function(data, responseCallback) {
		console.log("JS Echo called with:", data)
		responseCallback(data)
	})
	bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
		console.log("JS received response:", responseData)
	})
})
複製程式碼
  1. 初始化,得到bride物件。則可呼叫原生app已定義方法或註冊js方法供原生呼叫
setupWebViewJavascriptBridge(function(bridge) {
	
	/* Initialize your app here */

	bridge.registerHandler('JS Echo', function(data, responseCallback) {
		console.log("JS Echo called with:", data)
		responseCallback(data) // 
	})
	bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
		console.log("JS received response:", responseData)
	})
})
複製程式碼

Tips:

  • Android 與 IOS初化方式不同,需要判斷平臺後再進行呼叫。另外Android初始化時,需額外引入一些方法。
  • 呼叫Android定義方法時,返回值只能為字串。而IOS可為JSON物件。需要在callHandler時,對返回值進行封裝處理或統一規定好資料格式。
  • 完整業務程式碼文末給出

踩坑

  1. 呼叫bridge屬性方法registerHandler,callHandler,在回撥函式內處理頁面邏輯時,最好避免使用this
  2. vue元件下,在registerHandler,callHandler回撥函式內使用vue例項時,無法獲取例項物件。正確做法是在回撥函式內呼叫window物件下方法,再通過該方法去使用vue例項物件。
//vue 元件
mounted(){
    window['handleServicePushMessage'] = (res) => {
    	vm.handleServicePushMessage(res)
    };
    bridge.registerHandler("servicePushMessage", function (data, responseCallback) {
        handleServicePushMessage(data)
        responseCallback(data) //可傳值到App
    })
}
複製程式碼
  1. 桌面推送訊息點選跳轉至App內詳情情況下,js註冊方法供呼叫時,可能會引起重複呼叫的問題。故在方法內需做好重複呼叫判斷
  2. IOS-12.0版本下,在有輸入框的頁面,輸入時軟鍵盤會頂起webview,當失去焦點時,webview不會自動回彈。需呼叫APP做處理拉回介面。
//解決ios 12版本 ui不自動回拉問題
document.addEventListener('focusout', function (event) {
	let curTarget = event.target || event.srcElement;
	let isInput= ['input', 'textarea'];
	//處理頁面連續點選都為輸入框的情況
	let curTargetTagName= curTarget.tagName.toLowerCase();
	    if (isInput.includes(curTargetTagName)) {
    	    //事件處理
    	    //延遲獲取activeElement再進行判斷
        	setTimeout(function () {
        	    let activeEle = document.activeElement;
        	    let activeEleTagName= activeEle.tagName.toLowerCase();
        	    if (!isInput.includes(activeEleTagName)) {
        	        // console.log(document.activeElement.tagName);
        	        //呼叫app橋拉回webview
        	        performMethod('scrollTotop', null);
                    }
        	}, 200);
        }
}, true);
複製程式碼

5.當js呼叫app不存在的橋時,無法捕獲異常,頁面不會報錯
6.導航欄顯示問題,由於專案時間緊迫,並且app開發人員不承載太多開發任務,所以路由控制放在前端處理。此時就有導航欄電池時間欄的適配問題。本專案採用頂部下調20PX處理,電池時間欄字型顏色的控制也是通過橋呼叫來設定;另外iPhone X適配另外處理。
7.當app載入完網頁時,js立即呼叫原生方法橋時,可能出現原生方法橋未註冊完情況。故特殊情況需延遲呼叫橋操作。

完整程式碼

/*判斷平臺*/
function (window) {
	window.device = {};
	var ua = navigator.userAgent;
	var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
	var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
	var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
	var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
	device.ios = device.android = device.iphone = device.ipad = device.androidChrome = false;
	if (android) {
		device.os = 'android';
		device.osVersion = android[2];
		device.android = true;
		device.androidChrome = ua.toLowerCase().indexOf('chrome') >= 0
	}
	if (ipad || iphone || ipod) {
		device.os = 'ios';
		device.ios = true
	}
}(window)
/*引入Android需要的初始化,IOS不執行,如執行IOS端橋呼叫會受影響*/
(function () {
	if (window.WebViewJavascriptBridge || device.ios) {
		return false;
	}
	var messagingIframe;
	var sendMessageQueue = [];
	var receiveMessageQueue = [];
	var messageHandlers = {};
	var CUSTOM_PROTOCOL_SCHEME = 'yy';
	var QUEUE_HAS_MESSAGE = '__QUEUE_MESSAGE__/';
	var responseCallbacks = {};
	var uniqueId = 1;

	function _createQueueReadyIframe(doc) {
		messagingIframe = doc.createElement('iframe');
		messagingIframe.style.display = 'none';
		doc.documentElement.appendChild(messagingIframe);
	}

	/*set default messageHandler*/
	function init(messageHandler) {
		if (WebViewJavascriptBridge._messageHandler) {
			throw new Error('WebViewJavascriptBridge.init called twice');
		}
		WebViewJavascriptBridge._messageHandler = messageHandler;
		var receivedMessages = receiveMessageQueue;
		receiveMessageQueue = null;
		for (var i = 0; i < receivedMessages.length; i++) {
			_dispatchMessageFromNative(receivedMessages[i]);
		}
	}

	function send(data, responseCallback) {
		_doSend({data: data}, responseCallback);
	}

	function registerHandler(handlerName, handler) {
		messageHandlers[handlerName] = handler;
	}

	function callHandler(handlerName, data, responseCallback) {
		_doSend({handlerName: handlerName, data: data}, responseCallback);
	}

	/*sendMessage add message, 觸發native處理 sendMessage*/
	function _doSend(message, responseCallback) {
		if (responseCallback) {
			var callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime();
			responseCallbacks[callbackId] = responseCallback;
			message.callbackId = callbackId;
		}
		sendMessageQueue.push(message);
		messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
	}

	/* 提供給native呼叫,該函式作用:獲取sendMessageQueue返回給native,由於android不能直接獲取返回的內容,所以使用url shouldOverrideUrlLoading 的方式返回內容*/
	function _fetchQueue() {
		var messageQueueString = JSON.stringify(sendMessageQueue);
		sendMessageQueue = [];
		/*android can't read directly the return data, so we can reload iframe src to communicate with java*/
		messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://return/_fetchQueue/' + encodeURIComponent(messageQueueString);
	}

	/*提供給native使用,*/
	function _dispatchMessageFromNative(messageJSON) {
		setTimeout(function () {
			var message = JSON.parse(messageJSON);
			var responseCallback;
			/*java call finished, now need to call js callback function*/
			if (message.responseId) {
				responseCallback = responseCallbacks[message.responseId];
				if (!responseCallback) {
					return;
				}
				responseCallback(message.responseData);
				delete responseCallbacks[message.responseId];
			} else {/*直接傳送*/
				if (message.callbackId) {
					var callbackResponseId = message.callbackId;
					responseCallback = function (responseData) {
						_doSend({responseId: callbackResponseId, responseData: responseData});
					};
				}
				var handler = WebViewJavascriptBridge._messageHandler;
				if (message.handlerName) {
					handler = messageHandlers[message.handlerName];
				}
				/*查詢指定handler*/
				try {
					handler(message.data, responseCallback);
				} catch (exception) {
					if (typeof console != 'undefined') {
						console.log("WebViewJavascriptBridge: WARNING: javascript handler threw.", message, exception);
					}
				}
			}
		});
	}

	/*提供給native呼叫,receiveMessageQueue 在會在頁面載入完後賦值為null,所以*/
	function _handleMessageFromNative(messageJSON) {
		if (receiveMessageQueue && receiveMessageQueue.length > 0) {
			receiveMessageQueue.push(messageJSON);
		} else {
			_dispatchMessageFromNative(messageJSON);
		}
	}

	var WebViewJavascriptBridge = window.WebViewJavascriptBridge = {
		init: init,
		send: send,
		registerHandler: registerHandler,
		callHandler: callHandler,
		_fetchQueue: _fetchQueue,
		_handleMessageFromNative: _handleMessageFromNative
	};
	var doc = document;
	_createQueueReadyIframe(doc);
	var readyEvent = doc.createEvent('Events');
	readyEvent.initEvent('WebViewJavascriptBridgeReady');
	readyEvent.bridge = WebViewJavascriptBridge;
	doc.dispatchEvent(readyEvent);
})();
/*Android端初始化函式*/
function connectWebViewJavascriptBridge(callback) {
	if (window.WebViewJavascriptBridge) {
		callback(WebViewJavascriptBridge)
	} else {
		document.addEventListener('WebViewJavascriptBridgeReady', function () {
			callback(WebViewJavascriptBridge)
		}, false);
	}
}
/*IOS端初始化函式*/
function setupWebViewJavascriptBridge(callback) {
	if (window.WebViewJavascriptBridge) {
		return callback(WebViewJavascriptBridge)
	} else {
	}
	if (window.WVJBCallbacks) {
		return window.WVJBCallbacks.push(callback)
	}
	window.WVJBCallbacks = [callback];
	var WVJBIframe = document.createElement('iframe');
	WVJBIframe.style.display = 'none';
	WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
	document.documentElement.appendChild(WVJBIframe);
	setTimeout(function () {
		document.documentElement.removeChild(WVJBIframe)
	}, 0)
}
if(device.ios){
    setupWebViewJavascriptBridge(function(bridge){
        /*掛載上全域性物件*/
        window.BRIDGE= brige;
    })
}
if(device.android){
    connectWebViewJavascriptBridge(function(bridge){
        /*掛載上全域性物件*/
        window.BRIDGE= brige;
    })
}

複製程式碼

相關文章