• Stars
    star
    328
  • Rank 128,352 (Top 3 %)
  • Language
    Java
  • Created almost 7 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An Android bridge for sending messages between Java and JavaScript in WebView. and this is also a mirror of https://github.com/marcuswestin/WebViewJavascriptBridge which supports IOS platforms.

重要通知

由于DSBridge(笔者开发的一个更强大的跨平台JavaScript Bridge)目前已取得大量用户,由于笔者精力有限,为了集中精力打造精品,此项目将不再维护,笔者将把主要精力放到DSBridge的维护与支持上,也欢迎大家使用DSBridge。

DSBridge for Android: https://github.com/wendux/DSBridge-Android

DSBridge for iOS: https://github.com/wendux/DSBridge-IOS

WebViewJavascriptBridge

language license GitHub last commit

An Android bridge for sending messages between Java and JavaScript in WebView. and It is a mirror of marcuswestin/WebViewJavascriptBridge (object-c) and Lision/WKWebViewJavascriptBridge(swift) which supports IOS platforms.

Introduction

This Android version project is a mirror of marcuswestin/WebViewJavascriptBridge (object-c) and Lision/WKWebViewJavascriptBridge(swift), so there are some similarities between the two project , such as API design, native code, and the Javascript code is exactly the same.

Notice

If you are a new user, I strongly suggest that you use DSBridge instead. DSBridge is a modern cross-platform Javascript bridge, it is more powerful than WebViewJavascriptBridge.

Installation

  1. Add the JitPack repository to your build file

    allprojects {
      repositories {
        ...
        maven { url 'https://jitpack.io' }
      }
    }
  2. Add the dependency

    dependencies {
      compile 'com.github.wendux:WebViewJavascriptBridge:master-SNAPSHOT'
    }

Examples

See the wendu.jsbdemo/ folder. run the app project and to see it in action.

To use a WebViewJavascriptBridge in your own project:

Usage

  1. Use WVJBWebView instead of WebView:
import wendu.webviewjavascriptbridge.WVJBWebView

...

WVJBWebView webView = (WVJBWebView) findViewById(R.id.webview);
  1. Register a handler in Java, and call a JS handler:
webView.registerHandler("Java Echo", new WVJBWebView.WVJBHandler() {
  @Override
  public void handler(Object data, WVJBWebView.WVJBResponseCallback callback) {
    Log.d("wvjsblog", "Java Echo called with: "+data.toString());
    callback.onResult(data);
  }
});

webView.callHandler("JS Echo", null, new WVJBWebView.WVJBResponseCallback() {
  @Override
  public void onResult(Object data) {
    Log.d("wvjsblog", "Java received response: "+data.toString());
  }
});
  1. Copy and paste setupWebViewJavascriptBridge into your JS:
function setupWebViewJavascriptBridge(callback) {
  var bridge = window.WebViewJavascriptBridge || window.WKWebViewJavascriptBridge;
  if (bridge) { return callback(bridge); }
  var callbacks = window.WVJBCallbacks || window.WKWVJBCallbacks;
  if (callbacks) { return callbacks.push(callback); }
  window.WVJBCallbacks = window.WKWVJBCallbacks = [callback];
  if (window.WKWebViewJavascriptBridge) {
    //for https://github.com/Lision/WKWebViewJavascriptBridge
    window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null);
  } else {
    //for https://github.com/marcuswestin/WebViewJavascriptBridge
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'https://__bridge_loaded__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0);
	}
}
  1. Finally, call setupWebViewJavascriptBridge and then use the bridge to register handlers and call Java handlers:
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('Java Echo', {'key': 'value'}, function responseCallback(responseData) {
    console.log("JS received response:", responseData);
  });
});

API Reference

Java API

webview.registerHandler(String handlerName, WVJBHandler handler);

Register a handler called handlerName. The javascript can then call this handler with WebViewJavascriptBridge.callHandler("handlerName").

Example:

webView.registerHandler("getScreenHeight", new WVJBWebView.WVJBHandler() {
  @Override
  public void handler(Object data, WVJBWebView.WVJBResponseCallback callback) {
    //wm is WindowManager
    callback.onResult(wm.getDefaultDisplay().getHeight());
  }
});

webView.registerHandler("log", new WVJBWebView.WVJBHandler() {
  @Override
  public void handler(Object data, WVJBWebView.WVJBResponseCallback callback) {
    Log.d("wvjsblog", "Log: "+data.toString());
  }
});
webview.callHandler(String handlerName, WVJBResponseCallback responseCallback)
webview.callHandler(String handlerName, Object data,WVJBResponseCallback responseCallback)

Call the javascript handler called handlerName. If a responseCallback is given, the javascript handler can respond.

Example:

webview.callHandler("showAlert", "Hi from Java to JS!");
webview.callHandler("getCurrentPageUrl", null, new WVJBWebView.WVJBResponseCallback() {
  @Override
    public void onResult(Object data) {
    Log.d("wvjsblog", "Current WVJBWebView page URL is: %@"+data.toString());
  }
});
webview.disableJavascriptAlertBoxSafetyTimeout(bool disable)

UNSAFE. Speed up bridge message passing by disabling the setTimeout safety check. It is only safe to disable this safety check if you do not call any of the javascript popup box functions (alert, confirm, and prompt). If you call any of these functions from the bridged javascript code, the app will hang.

Example:

webview.disableJavascriptAlertBoxSafetyTimeout(true);

Javascript API

bridge.registerHandler("handlerName", function(responseData) { ... })

Register a handler called handlerName. The Java can then call this handler with webview callHandler("handlerName","Foo") and webview.callHandler("handlerName", "Foo", new WVJBWebView.WVJBResponseCallback() {...})

Example:

bridge.registerHandler("showAlert", function(data) { alert(data) })
bridge.registerHandler("getCurrentPageUrl", function(data, responseCallback) {
  responseCallback(document.location.toString())
})
bridge.callHandler("handlerName", data)
bridge.callHandler("handlerName", data, function responseCallback(responseData) { ... })

Call an Java handler called handlerName. If a responseCallback function is given the Java handler can respond.

Example:

bridge.callHandler("Log", "Foo")
bridge.callHandler("getScreenHeight", null, function(response) {
  alert('Screen height:' + response)
})
bridge.disableJavascriptAlertBoxSafetyTimeout(...)

Calling bridge.disableJavascriptAlertBoxSafetyTimeout(...) has the same effect as calling webview disableJavscriptAlertBoxSafetyTimeout(...) in Java.

Example:

//disable
bridge.disableJavascriptAlertBoxSafetyTimeout()
//enable
bridge.disableJavascriptAlertBoxSafetyTimeout(false)

Expansion For Android

In this Android version, I have added a way to judge whether the handler (Javascript and java) exists.

In Java

webview.hasJavascriptMethod(String handlerName,  WVJBMethodExistCallback callback)

For example:

webView.hasJavascriptMethod("echoHandler", new WVJBWebView.WVJBMethodExistCallback() {
  @Override
  public void onResult(boolean exist) {
    if(exist) {
      Log.d("wvjsblog", "Javascript handler 'echoHandler' exist. ");
    }
  }
});

In Javascript

bridge.hasNativeMethod("handlerName", function responseCallback(responseData){...})

For example:

bridge.hasNativeMethod('javaEchoToJs', function(exist){
  if(exist){
    console.log("Native method 'javaEchoToJs' exist! ")
  }
})

Compare with DSBridge

DSBridge is a modern cross-platform JavaScript bridge, through which you can invoke each other's functions synchronously or asynchronously between JavaScript and native applications. On the whole, DSBridge is more powerful than WebViewJavascriptBridge. If you are a new user, I strongly suggest that you use DSBridge instead. More details please rerfer to https://github.com/wendux/DSBridge-Android.

More Repositories

1

fly

🚀 Supporting request forwarding and Promise based HTTP client for all JavaScript runtimes.
JavaScript
3,896
star
2

DSBridge-Android

🌎 A modern cross-platform JavaScript bridge, through which you can invoke each other's functions synchronously or asynchronously between JavaScript and native.
Java
3,755
star
3

ajax-hook

Intercepting browser's http requests which made by XMLHttpRequest.
JavaScript
2,572
star
4

DSBridge-IOS

🌏 A modern cross-platform JavaScript bridge, through which you can invoke each other's functions synchronously or asynchronously between JavaScript and native.
Objective-C
1,950
star
5

flutter_in_action_source_code

《Flutter实战》随书源码
Dart
795
star
6

grace

一个精巧、易用的微信小程序开发辅助库
JavaScript
407
star
7

flutter_in_action_2

Flutter实战第二版随书源码
Dart
181
star
8

neat

🎈 Neat是一个追求极致优雅,高效,简洁,只为现代浏览器的,jQuery兼容的JavaScript库,只有3.7K(gzip)!
JavaScript
117
star
9

DSpiderDemo-Android

客户端爬虫安卓端demo
Java
43
star
10

DSpiderDemo-ios

客户端爬虫ios端demo
Objective-C
36
star
11

gitme

Good stuff is worth waiting for.
23
star
12

keep-loader

一个用于在不同的打包环境下生成不同的代码的Webpack loader,就像C/C++中的宏特性一样。提供了一种在源码中控制打包阶段生成不同代码的能力。
JavaScript
18
star
13

es6-promise-always

Extend method always for es6 Promise object
JavaScript
12
star
14

flutter-comment

Flutter中文网评论
10
star
15

style-selector-jQuery-plugin

Custom jQuery selector, through which we can choose the specified CSS style characteristics of the DOM elements.
HTML
7
star
16

wendux.github.io

博客
Vue
6
star
17

comment-test

2
star
18

neat-official-website

The official website source code of Neat.js
JavaScript
1
star
19

Android-WaveProgressBar

Android波浪进度条,支持圆形、矩形,支持背景色圆形。
Java
1
star
20

MPA-Boilerplate

多页面web应用脚手架
JavaScript
1
star
21

node-http-static-server

Node http server for static files.
JavaScript
1
star