Skip to content

Commit

Permalink
fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
uknownothingsnow committed Sep 8, 2022
1 parent 94b9d31 commit 6bef4a7
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 91 deletions.
6 changes: 3 additions & 3 deletions example/src/main/assets/demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@

//send message to native
var data = {id: 1, content: "这是一个图片 <img src=\"a.png\"/> test\r\nhahaha"};
window.WebViewJavascriptBridge.send(
WebViewJavascriptBridge.doSend(
data
, function(responseData) {
document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData
Expand Down Expand Up @@ -75,7 +75,7 @@
}

function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
if (window.WebViewJavascriptBridge && WebViewJavascriptBridge.inited) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
Expand All @@ -102,7 +102,7 @@
});

bridge.registerHandler("functionInJs", function(data, responseCallback) {
document.getElementById("show").innerHTML = ("data from Java: = " + data);
document.getElementById("show").innerHTML = ("data from Java: = " + data + Date.now());
if (responseCallback) {
var responseData = "Javascript Says Right back aka!";
responseCallback(responseData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeHelper;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.IWebView;
import com.github.lzyzsd.jsbridge.OnBridgeCallback;
import com.github.lzyzsd.jsbridge.WebViewJavascriptBridge;

/**
Expand Down Expand Up @@ -69,17 +69,6 @@ public void setDefaultHandler(BridgeHandler handler) {
bridgeHelper.setDefaultHandler(handler);
}

@Override
public void send(String data) {
send(data, null);
}

@Override
public void send(String data, CallBackFunction responseCallback) {
bridgeHelper.send(data, responseCallback);
}


/**
* register handler,so that javascript can call it
* 注册处理程序,以便javascript调用它
Expand Down Expand Up @@ -108,8 +97,22 @@ public void unregisterHandler(String handlerName) {
* @param data data
* @param callBack CallBackFunction
*/
public void callHandler(String handlerName, String data, CallBackFunction callBack) {
public void callHandler(String handlerName, String data, OnBridgeCallback callBack) {
bridgeHelper.callHandler(handlerName, data, callBack);
}

@Override
public void sendToWeb(String data) {
sendToWeb(data, (OnBridgeCallback) null);
}

@Override
public void sendToWeb(String data, OnBridgeCallback responseCallback) {
bridgeHelper.sendToWeb(data, responseCallback);
}

@Override
public void sendToWeb(String function, Object... values) {
bridgeHelper.sendToWeb(function, values);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,9 @@ public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathC
}
});

webView.addJavascriptInterface(new MainJavascrotInterface(webView.getCallbacks(), webView), "android");
webView.addJavascriptInterface(new MainJavascriptInterface(webView.getCallbacks(), webView), "WebViewJavascriptBridge");
webView.setGson(new Gson());
webView.loadUrl("file:///android_asset/demo.html");

User user = new User();
Location location = new Location();
location.address = "SDU";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,19 @@
* Author: bigwang
* Description:
*/
public class MainJavascrotInterface extends BridgeWebView.BaseJavascriptInterface {
public class MainJavascriptInterface extends BridgeWebView.BaseJavascriptInterface {

private BridgeWebView mWebView;

public MainJavascrotInterface(Map<String, OnBridgeCallback> callbacks, BridgeWebView webView) {
public MainJavascriptInterface(Map<String, OnBridgeCallback> callbacks, BridgeWebView webView) {
super(callbacks);
mWebView = webView;
}

public MainJavascriptInterface(Map<String, OnBridgeCallback> callbacks) {
super(callbacks);
}

@Override
public String send(String data) {
return "it is default response";
Expand All @@ -30,7 +34,7 @@ public String send(String data) {

@JavascriptInterface
public void submitFromWeb(String data, String callbackId) {
Log.d("chromium data", data + ", callbackId: " + callbackId + " " + Thread.currentThread().getName());
Log.d("MainJavascriptInterface", data + ", callbackId: " + callbackId + " " + Thread.currentThread().getName());
mWebView.sendResponse("submitFromWeb response", callbackId);
}
}
51 changes: 27 additions & 24 deletions library/src/main/assets/WebViewJavascriptBridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,51 @@
//since comments will cause error when use in webview.loadurl,
//comments will be remove by java use regexp
(function() {
if (window.WebViewJavascriptBridge) {
if (window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.inited) {
return;
}

var receiveMessageQueue = [];
var messageHandlers = {};
var sendMessageQueue = [];

var responseCallbacks = {};
var uniqueId = 1;

var lastCallTime = 0;
var stoId = null;
var FETCH_QUEUE_INTERVAL = 20;
var messagingIframe;
var CUSTOM_PROTOCOL_SCHEME = "yy";
var QUEUE_HAS_MESSAGE = "__QUEUE_MESSAGE__";

// 创建消息index队列iframe
function _createQueueReadyIframe(doc) {
messagingIframe = doc.createElement('iframe');
function _createQueueReadyIframe() {
messagingIframe = document.createElement('iframe');
messagingIframe.style.display = 'none';
doc.documentElement.appendChild(messagingIframe);
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
document.documentElement.appendChild(messagingIframe);
}
//创建消息体队列iframe
function _createQueueReadyIframe4biz(doc) {
bizMessagingIframe = doc.createElement('iframe');
function _createQueueReadyIframe4biz() {
bizMessagingIframe = document.createElement('iframe');
bizMessagingIframe.style.display = 'none';
doc.documentElement.appendChild(bizMessagingIframe);
document.documentElement.appendChild(bizMessagingIframe);
}
//set default messageHandler 初始化默认的消息线程
function init(messageHandler) {
if (WebViewJavascriptBridge._messageHandler) {
throw new Error('WebViewJavascriptBridge.init called twice');
}
_createQueueReadyIframe();
_createQueueReadyIframe4biz();
WebViewJavascriptBridge._messageHandler = messageHandler;
var receivedMessages = receiveMessageQueue;
receiveMessageQueue = null;
for (var i = 0; i < receivedMessages.length; i++) {
_dispatchMessageFromNative(receivedMessages[i]);
}
WebViewJavascriptBridge.inited = true;
}

// 发送
Expand Down Expand Up @@ -73,14 +81,13 @@
callbackId = '';
}
try {
var fn = eval('window.android.' + handlerName);
var fn = eval('WebViewJavascriptBridge.' + handlerName);
} catch(e) {
console.log(e);
}
if (typeof fn === 'function'){
var responseData = fn.call(this, JSON.stringify(message), callbackId);
var responseData = fn.call(WebViewJavascriptBridge, JSON.stringify(message), callbackId);
if(responseData){
console.log('response message: '+ responseData);
responseCallback = responseCallbacks[callbackId];
if (!responseCallback) {
return;
Expand All @@ -96,7 +103,7 @@

// 提供给native调用,该函数作用:获取sendMessageQueue返回给native,由于android不能直接获取返回的内容,所以使用url shouldOverrideUrlLoading 的方式返回内容
function _fetchQueue() {
// 空数组直接返回
// 空数组直接返回
if (sendMessageQueue.length === 0) {
return;
}
Expand Down Expand Up @@ -157,30 +164,26 @@

//提供给native调用,receiveMessageQueue 在会在页面加载完后赋值为null,所以
function _handleMessageFromNative(messageJSON) {
console.log('handle message: '+ messageJSON);
if (receiveMessageQueue) {
receiveMessageQueue.push(messageJSON);
}
_dispatchMessageFromNative(messageJSON);

}

var WebViewJavascriptBridge = window.WebViewJavascriptBridge = {
init: init,
send: send,
registerHandler: registerHandler,
callHandler: callHandler,
_handleMessageFromNative: _handleMessageFromNative
};
WebViewJavascriptBridge.init = init;
WebViewJavascriptBridge.doSend = send;
WebViewJavascriptBridge.registerHandler = registerHandler;
WebViewJavascriptBridge.callHandler = callHandler;
WebViewJavascriptBridge._handleMessageFromNative = _handleMessageFromNative;

var doc = document;
var readyEvent = doc.createEvent('Events');
var readyEvent = document.createEvent('Events');
var jobs = window.WVJBCallbacks || [];
readyEvent.initEvent('WebViewJavascriptBridgeReady');
readyEvent.bridge = WebViewJavascriptBridge;
window.WVJBCallbacks = []
window.WVJBCallbacks = [];
jobs.forEach(function (job) {
job(WebViewJavascriptBridge)
})
doc.dispatchEvent(readyEvent);
});
document.dispatchEvent(readyEvent);
})();
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.github.lzyzsd.jsbridge;

public interface BridgeHandler {
void handler(String data, OnBridgeCallback callBackFunction);
}
49 changes: 29 additions & 20 deletions library/src/main/java/com/github/lzyzsd/jsbridge/BridgeHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class BridgeHelper implements WebViewJavascriptBridge {
private static final String TAG = "BridgeHelper";

private static final String BRIDGE_JS = "WebViewJavascriptBridge.js";
private Map<String, CallBackFunction> responseCallbacks = new HashMap<>();
private Map<String, OnBridgeCallback> responseCallbacks = new HashMap<>();
private Map<String, BridgeHandler> messageHandlers = new HashMap<>();
private BridgeHandler defaultHandler = new DefaultHandler();

Expand Down Expand Up @@ -61,32 +61,22 @@ public void setDefaultHandler(BridgeHandler handler) {
*/
private void handlerReturnData(String url) {
String functionName = BridgeUtil.getFunctionFromReturnUrl(url);
CallBackFunction f = responseCallbacks.get(functionName);
OnBridgeCallback f = responseCallbacks.get(functionName);
String data = BridgeUtil.getDataFromReturnUrl(url);
if (f != null) {
f.onCallBack(data);
responseCallbacks.remove(functionName);
}
}

@Override
public void send(String data) {
send(data, null);
}

@Override
public void send(String data, CallBackFunction responseCallback) {
doSend(null, data, responseCallback);
}

/**
* 保存message到消息队列
*
* @param handlerName handlerName
* @param data data
* @param responseCallback CallBackFunction
*/
private void doSend(String handlerName, String data, CallBackFunction responseCallback) {
private void doSend(String handlerName, String data, OnBridgeCallback responseCallback) {
Message m = new Message();
if (!TextUtils.isEmpty(data)) {
m.setData(data);
Expand Down Expand Up @@ -141,7 +131,7 @@ private void dispatchMessage(Message m) {
*/
private void flushMessageQueue() {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
loadUrl(BridgeUtil.JS_FETCH_QUEUE_FROM_JAVA, new CallBackFunction() {
loadUrl(BridgeUtil.JS_FETCH_QUEUE_FROM_JAVA, new OnBridgeCallback() {

@Override
public void onCallBack(String data) {
Expand All @@ -161,16 +151,16 @@ public void onCallBack(String data) {
String responseId = m.getResponseId();
// 是否是response CallBackFunction
if (!TextUtils.isEmpty(responseId)) {
CallBackFunction function = responseCallbacks.get(responseId);
OnBridgeCallback function = responseCallbacks.get(responseId);
String responseData = m.getResponseData();
function.onCallBack(responseData);
responseCallbacks.remove(responseId);
} else {
CallBackFunction responseFunction = null;
OnBridgeCallback responseFunction = null;
// if had callbackId 如果有回调Id
final String callbackId = m.getCallbackId();
if (!TextUtils.isEmpty(callbackId)) {
responseFunction = new CallBackFunction() {
responseFunction = new OnBridgeCallback() {
@Override
public void onCallBack(String data) {
Message responseMsg = new Message();
Expand All @@ -180,7 +170,7 @@ public void onCallBack(String data) {
}
};
} else {
responseFunction = new CallBackFunction() {
responseFunction = new OnBridgeCallback() {
@Override
public void onCallBack(String data) {
// do nothing
Expand All @@ -204,7 +194,7 @@ public void onCallBack(String data) {
}
}

private void loadUrl(String jsUrl, CallBackFunction returnCallback) {
private void loadUrl(String jsUrl, OnBridgeCallback returnCallback) {
this.loadUrl(jsUrl);
// 添加至 Map<String, CallBackFunction>
responseCallbacks.put(BridgeUtil.parseFunctionName(jsUrl), returnCallback);
Expand Down Expand Up @@ -247,7 +237,7 @@ public void unregisterHandler(String handlerName) {
* @param data data
* @param callBack CallBackFunction
*/
public void callHandler(String handlerName, String data, CallBackFunction callBack) {
public void callHandler(String handlerName, String data, OnBridgeCallback callBack) {
doSend(handlerName, data, callBack);
}

Expand Down Expand Up @@ -285,4 +275,23 @@ public boolean shouldOverrideUrlLoading(String url) {
}
return false;
}

@Override
public void sendToWeb(String data) {
sendToWeb(data, (OnBridgeCallback) null);
}

@Override
public void sendToWeb(String data, OnBridgeCallback responseCallback) {
doSend(null, data, responseCallback);
}

@Override
public void sendToWeb(String function, Object... values) {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
String jsCommand = String.format(function, values);
jsCommand = String.format(BridgeUtil.JAVASCRIPT_STR, jsCommand);
loadUrl(jsCommand);
}
}
}
Loading

0 comments on commit 6bef4a7

Please sign in to comment.