About this project
JsBridge is a bridge library for bidirectional communication between Android WebView and JavaScript, inspired by WeChat's WebView JsBridge implementation. It provides a secure and reliable message passing mechanism, supporting both Java-to-JavaScript and JavaScript-to-Java calls.
## Key Features
- **Bidirectional Communication**: Supports calls in both directions between Java and JavaScript, with a callback mechanism.
- **Multiple Communication Channels**: Supports four channels: URL Scheme interception, @JavascriptInterface, evaluateJavascript(), and loadUrl("javascript:"), compatible with different Android versions.
- **Persistent Callbacks**: Supports callbacks with multiple responses, suitable for real-time updates, event streams, and other scenarios.
- **Domain Whitelist**: Can restrict which domains can call native methods, enhancing security.
- **Message Queue**: Messages sent before JS injection completes are automatically queued and dispatched uniformly after injection, preventing message loss.
- **Custom WebView Integration**: Can be easily integrated into custom WebViews via BridgeHelper.
## Installation
Add the dependency via the JitPack repository:
```groovy
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
implementation 'com.github.happydog-intj:JsBridge:v2.1.0'
}
```
## Quick Start
### Using BridgeWebView
Add BridgeWebView to your layout and initialize it in the Activity:
```java
BridgeWebView webView = findViewById(R.id.webView);
webView.setGson(new Gson());
webView.addJavascriptInterface(
new MainJavascriptInterface(
webView.getCallbacks(),
webView.getPersistentCallbacks(),
webView),
"WebViewJavascriptBridge");
webView.loadUrl("file:///android_asset/demo.html");
```
### Java Calling JavaScript
Register a handler on the JS side, then call it from Java:
```javascript
WebViewJavascriptBridge.registerHandler("functionInJs", function(data, responseCallback) {
document.getElementById("show").innerHTML = "data from Java: = " + data;
responseCallback("Javascript Says Right back aka!");
});
```
```java
webView.callHandler("functionInJs", new Gson().toJson(user), new OnBridgeCallback() {
@Override
public void onCallBack(String data) {
Log.d(TAG, "response from JS: " + data);
}
});
```
### JavaScript Calling Java
Create a @JavascriptInterface class, and the JS side can call it:
```java
public class MainJavascriptInterface extends BridgeWebView.BaseJavascriptInterface {
@JavascriptInterface
public void submitFromWeb(String data, String callbackId) {
Log.d("JSInterface", "data from web: " + data);
mWebView.responseFromWeb("response from Java", callbackId);
}
}
```
```javascript
WebViewJavascriptBridge.callHandler(
'submitFromWeb',
{'param': 'value'},
function(responseData) {
document.getElementById("show").innerHTML = "response: " + responseData;
}
);
```
### Persistent Callbacks
By default, callbacks are automatically deleted after the first call. Use `callHandlerPersistent()` for multiple responses:
```java
webView.callHandlerPersistent("functionInJs", data, new OnBridgeCallback() {
@Override
public void onCallBack(String data) {
Log.d(TAG, "called again: " + data);
}
});
```
### Domain Whitelist
Restrict which domains can call native methods:
```java
webView.addAllowedHost("example.com");
webView.addAllowedHost("*.example.com");
```
When the whitelist is empty (default), all domains are allowed.
## Custom WebView Integration
Integrate into a custom WebView via BridgeHelper:
```java
public class CustomWebView extends WebView implements WebViewJavascriptBridge, IWebView {
private BridgeHelper bridgeHelper;
private void init() {
getSettings().setJavaScriptEnabled(true);
bridgeHelper = new BridgeHelper(this);
setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
bridgeHelper.onPageStarted();
}
@Override
public void onPageFinished(WebView view, String url) {
bridgeHelper.onPageFinished();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return bridgeHelper.shouldOverrideUrlLoading(url);
}
});
}
}
```
## Compatibility
- **Android 11+ (API 30+)**: Adapted, file access permissions are disabled by default, and cache strategy is determined by the host app.
- **HarmonyOS**: Community provides a ported version `@alvin917/jsbridge`.
- **Embedded Devices**: If WebView creation crashes, check the device's WebView provider.
## License
MIT License.
Comments
0 Rating appears after 10 ratings
Sign in to join the discussion.