/
CommunicationBridge.java
192 lines (168 loc) · 6.9 KB
/
CommunicationBridge.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package org.wikipedia.bridge;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.wikipedia.dataclient.RestService;
import org.wikipedia.dataclient.ServiceFactory;
import org.wikipedia.json.GsonUtil;
import org.wikipedia.page.PageTitle;
import org.wikipedia.util.UriUtil;
import org.wikipedia.util.log.L;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Two-way communications bridge between JS in a WebView and Java.
*
* Messages TO the WebView are sent by calling loadUrl() with the Javascript payload in it.
*
* Messages FROM the WebView are received by leveraging @JavascriptInterface methods.
*
*/
public class CommunicationBridge {
private final Map<String, List<JSEventListener>> eventListeners;
private final CommunicationBridgeListener communicationBridgeListener;
private boolean isDOMReady;
private final List<String> pendingJSMessages = new ArrayList<>();
private final Map<String, ValueCallback<String>> pendingEvals = new HashMap<>();
public interface JSEventListener {
void onMessage(String messageType, JsonObject messagePayload);
}
public interface CommunicationBridgeListener {
WebView getWebView();
PageTitle getPageTitle();
}
@SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled"})
public CommunicationBridge(CommunicationBridgeListener communicationBridgeListener) {
this.communicationBridgeListener = communicationBridgeListener;
this.communicationBridgeListener.getWebView().getSettings().setJavaScriptEnabled(true);
this.communicationBridgeListener.getWebView().getSettings().setAllowUniversalAccessFromFileURLs(true);
this.communicationBridgeListener.getWebView().getSettings().setMediaPlaybackRequiresUserGesture(false);
this.communicationBridgeListener.getWebView().setWebChromeClient(new CommunicatingChrome());
this.communicationBridgeListener.getWebView().addJavascriptInterface(new PcsClientJavascriptInterface(), "pcsClient");
eventListeners = new HashMap<>();
}
public void onPageFinished() {
isDOMReady = true;
flushMessages();
}
public void resetHtml(@NonNull PageTitle pageTitle) {
isDOMReady = false;
pendingJSMessages.clear();
pendingEvals.clear();
communicationBridgeListener.getWebView().loadUrl(UriUtil
.encodeOkHttpUrl(ServiceFactory.getRestBasePath(pageTitle.getWikiSite()) + RestService.PAGE_HTML_ENDPOINT,
pageTitle.getPrefixedText()));
}
public void cleanup() {
pendingJSMessages.clear();
pendingEvals.clear();
eventListeners.clear();
if (incomingMessageHandler != null) {
incomingMessageHandler.removeCallbacksAndMessages(null);
incomingMessageHandler = null;
}
}
public void addListener(String type, JSEventListener listener) {
if (eventListeners.containsKey(type)) {
eventListeners.get(type).add(listener);
} else {
List<JSEventListener> listeners = new ArrayList<>();
listeners.add(listener);
eventListeners.put(type, listeners);
}
}
public void execute(@NonNull String js) {
String jsString = "javascript:" + js;
pendingJSMessages.add(jsString);
flushMessages();
}
public void evaluate(@NonNull String js, ValueCallback<String> callback) {
pendingEvals.put(js, callback);
flushMessages();
}
private void flushMessages() {
if (!isDOMReady) {
return;
}
for (String jsString : pendingJSMessages) {
communicationBridgeListener.getWebView().loadUrl(jsString);
}
pendingJSMessages.clear();
for (String key : pendingEvals.keySet()) {
communicationBridgeListener.getWebView().evaluateJavascript(key, pendingEvals.get(key));
}
pendingEvals.clear();
}
private static final int MESSAGE_HANDLE_MESSAGE_FROM_JS = 1;
private Handler incomingMessageHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
BridgeMessage message = (BridgeMessage) msg.obj;
if (!eventListeners.containsKey(message.getAction())) {
L.e("No such message type registered: " + message.getAction());
return false;
}
try {
List<JSEventListener> listeners = eventListeners.get(message.getAction());
for (JSEventListener listener : listeners) {
listener.onMessage(message.getAction(), message.getData());
}
} catch (Exception e) {
e.printStackTrace();
L.logRemoteError(e);
}
return false;
}
});
private class CommunicatingChrome extends WebChromeClient {
@Override
public boolean onConsoleMessage(@NonNull ConsoleMessage consoleMessage) {
L.d(consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + " - " + consoleMessage.message());
return true;
}
}
private class PcsClientJavascriptInterface {
/**
* Called from Javascript to send a message packet to the Java layer. The message must be
* formatted in JSON, and URL-encoded.
*
* @param message JSON structured message received from the WebView.
*/
@JavascriptInterface
public synchronized void onReceiveMessage(String message) {
if (incomingMessageHandler != null) {
Message msg = Message.obtain(incomingMessageHandler, MESSAGE_HANDLE_MESSAGE_FROM_JS,
GsonUtil.getDefaultGson().fromJson(message, BridgeMessage.class));
incomingMessageHandler.sendMessage(msg);
}
}
@JavascriptInterface
public synchronized String getSetupSettings() {
return JavaScriptActionHandler.setUp(communicationBridgeListener.getWebView().getContext(),
communicationBridgeListener.getPageTitle());
}
}
@SuppressWarnings("unused")
private class BridgeMessage {
@Nullable private String action;
@Nullable private JsonObject data;
@NonNull public String getAction() {
return StringUtils.defaultString(action);
}
@Nullable public JsonObject getData() {
return data;
}
}
}