diff --git a/library/src/main/assets/WebViewJavascriptBridge.js b/library/src/main/assets/WebViewJavascriptBridge.js index f5ba3dc..bf43554 100644 --- a/library/src/main/assets/WebViewJavascriptBridge.js +++ b/library/src/main/assets/WebViewJavascriptBridge.js @@ -12,6 +12,22 @@ var responseCallbacks = {}; var uniqueId = 1; + var lastCallTime = 0; + var stoId = null; + var FETCH_QUEUE_INTERVAL = 20; + + // 创建消息index队列iframe + function _createQueueReadyIframe(doc) { + messagingIframe = doc.createElement('iframe'); + messagingIframe.style.display = 'none'; + doc.documentElement.appendChild(messagingIframe); + } + //创建消息体队列iframe + function _createQueueReadyIframe4biz(doc) { + bizMessagingIframe = doc.createElement('iframe'); + bizMessagingIframe.style.display = 'none'; + doc.documentElement.appendChild(bizMessagingIframe); + } //set default messageHandler 初始化默认的消息线程 function init(messageHandler) { if (WebViewJavascriptBridge._messageHandler) { @@ -52,6 +68,7 @@ } else if (responseCallback) { callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime(); responseCallbacks[callbackId] = responseCallback; + message.callbackId = callbackId; }else{ callbackId = ''; } @@ -72,6 +89,32 @@ delete responseCallbacks[callbackId]; } } + + sendMessageQueue.push(message); + messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE; + } + + // 提供给native调用,该函数作用:获取sendMessageQueue返回给native,由于android不能直接获取返回的内容,所以使用url shouldOverrideUrlLoading 的方式返回内容 + function _fetchQueue() { + // 空数组直接返回 + if (sendMessageQueue.length === 0) { + return; + } + + // _fetchQueue 的调用间隔过短,延迟调用 + if (new Date().getTime() - lastCallTime < FETCH_QUEUE_INTERVAL) { + if (!stoId) { + stoId = setTimeout(_fetchQueue, FETCH_QUEUE_INTERVAL); + } + return; + } + + lastCallTime = new Date().getTime(); + stoId = null; + var messageQueueString = JSON.stringify(sendMessageQueue); + sendMessageQueue = []; + //android can't read directly the return data, so we can reload iframe src to communicate with java + bizMessagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://return/_fetchQueue/' + encodeURIComponent(messageQueueString); } //提供给native使用,