• Stars
    star
    9,450
  • Rank 3,772 (Top 0.08 %)
  • Language
    Java
  • Created over 9 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

android java and javascript bridge, inspired by wechat webview jsbridge

JsBridge


inspired and modified from this and wechat jsBridge file, with some bugs fix and feature enhancement.

This project make a bridge between Java and JavaScript.

It provides safe and convenient way to call Java code from js and call js code from java.

Demo

JsBridge Demo

Usage

JitPack.io

I strongly recommend https://jitpack.io

repositories {
    // ...
    maven { url "https://jitpack.io" }
}

dependencies {
    compile 'com.github.lzyzsd:jsbridge:1.0.4'
}

Use it in Java

add com.github.lzyzsd.jsbridge.BridgeWebView to your layout, it is inherited from WebView.

Register a Java handler function so that js can call

    webView.registerHandler("submitFromWeb", new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            Log.i(TAG, "handler = submitFromWeb, data from web = " + data);
            function.onCallBack("submitFromWeb exe, response data from Java");
        }
    });

js can call this Java handler method "submitFromWeb" through:

    WebViewJavascriptBridge.callHandler(
        'submitFromWeb'
        , {'param': str1}
        , function(responseData) {
            document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData
        }
    );

You can set a default handler in Java, so that js can send message to Java without assigned handlerName

    webView.setDefaultHandler(new DefaultHandler());
    window.WebViewJavascriptBridge.doSend(
        data
        , function(responseData) {
            document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData
        }
    );

Register a JavaScript handler function so that Java can call

    WebViewJavascriptBridge.registerHandler("functionInJs", function(data, responseCallback) {
        document.getElementById("show").innerHTML = ("data from Java: = " + data);
        var responseData = "Javascript Says Right back aka!";
        responseCallback(responseData);
    });

Java can call this js handler function "functionInJs" through:

    webView.callHandler("functionInJs", new Gson().toJson(user), new CallBackFunction() {
        @Override
        public void onCallBack(String data) {

        }
    });

You can also define a default handler use init method, so that Java can send message to js without assigned handlerName

for example:

    window.WebViewJavascriptBridge.init(function(message, responseCallback) {
        console.log('JS got a message', message);
        var data = {
            'Javascript Responds': 'Wee!'
        };
        console.log('JS responding with', data);
        responseCallback(data);
    });
    webView.send("hello");

will print 'JS got a message hello' and 'JS responding with' in webview console.

Notice

This lib will inject a WebViewJavascriptBridge Object to window object. You can listen to WebViewJavascriptBridgeReady event to ensure window.WebViewJavascriptBridge is exist, as the blow code shows:

    if (window.WebViewJavascriptBridge) {
        //do your work here
    } else {
        document.addEventListener(
            'WebViewJavascriptBridgeReady'
            , function() {
                //do your work here
            },
            false
        );
    }

Or put all JsBridge function call into window.WVJBCallbacks array if window.WebViewJavascriptBridge is undefined, this task queue will be flushed when WebViewJavascriptBridgeReady event triggered.

Copy and paste setupWebViewJavascriptBridge into your JS:

function setupWebViewJavascriptBridge(callback) {
	if (window.WebViewJavascriptBridge) {
        return callback(WebViewJavascriptBridge);
    }
	if (window.WVJBCallbacks) {
        return window.WVJBCallbacks.push(callback);
    }
	window.WVJBCallbacks = [callback];
}

Call setupWebViewJavascriptBridge and then use the bridge to register handlers or call Java handlers:

setupWebViewJavascriptBridge(function(bridge) {
	bridge.registerHandler('JS Echo', function(data, responseCallback) {
		console.log("JS Echo called with:", data);
		responseCallback(data);
    });
	bridge.callHandler('ObjC Echo', {'key':'value'}, function(responseData) {
		console.log("JS received response:", responseData);
	});
});

It same with https://github.com/marcuswestin/WebViewJavascriptBridge, that would be easier for you to define same behavior in different platform between Android and iOS. Meanwhile, writing concise code.

License

This project is licensed under the terms of the MIT license.

More Repositories

1

Awesome-RxJava

RxJava resources
4,830
star
2

CircleProgress

CircleProgress, DonutProgress, ArcProgress
Java
3,783
star
3

AndroidRandomColor

android random color generator library
Java
282
star
4

LoadingLayout

Android LoadingLayout
Java
193
star
5

SwipeLayout

android swipe gesture detector layout
Java
172
star
6

AndroidSeekAttention

Android的抖动动画,用于吸引用户注意
Java
160
star
7

AndroidHotFixExamples

demo how to implement Android HotFix
Java
132
star
8

custom-animations-with-fragment

使用animation和fragment改善Android表单
Java
33
star
9

awesome-remotes

great remote companies,各种很酷的远程工作的公司
32
star
10

AndroidStockChart

android stock chart
Java
31
star
11

androidcn.org

androidcn.org社区源码,修改自nodeclub
JavaScript
23
star
12

DingDingHeader

模仿钉钉头部滑动动画
Java
20
star
13

SweetAlertDialog

修改自https://github.com/pedant/sweet-alert-dialog
Java
18
star
14

blog

My Blog
HTML
18
star
15

MemoryBugs

Demos of potential memory bugs
Java
16
star
16

RxJavaExamples

demo RxJava and RxAndroid
Java
14
star
17

ZhihuDaily

知乎日报Android APP山寨版
Java
11
star
18

LeakMemoryExample

内存优化课程demo
Java
7
star
19

ListViewScrollViewDemo

仿雪球行情页底部的滑动手势效果
Java
7
star
20

MyWeiCiYuan

我自己定制的四次元微博客户端,按自己的使用习惯定制,私人定制,哈哈
Java
6
star
21

JavascriptBridgeDemo

Java
4
star
22

AndroidOverDraw

性能优化第二课,视图优化
Java
4
star
23

Kotlin-Guide

Kotlin Guide in Chinese
3
star
24

AndroidUIPorblems

show some ui common overdraw problems
Java
3
star
25

gowechat

golang wechat lib
JavaScript
3
star
26

adbs

adb extension use Node.js
JavaScript
2
star
27

InfiniteLoadingExample

android listview infinite loading example
Java
2
star
28

jobs

工作机会
2
star
29

Awesome-Kotlin

Kotlin resources
2
star
30

ZhihuDailyKotlin

山寨知乎日报Android,使用Kotlin写
Kotlin
2
star
31

golang-chat

golang chat server
Go
2
star
32

ImageLoader

Java
1
star
33

Calculator

Calculator learn iPhone development trails
Objective-C
1
star
34

AndroidWizard

android form wizard
Java
1
star
35

ReposDemo

first repos
1
star
36

DataStructure

DataStructure
Python
1
star
37

GitPresentationDemo

demo how to use git to present my project
1
star
38

helloworld

some code about gae
Python
1
star
39

oschina

oschina android client
Java
1
star
40

library

JavaScript
1
star
41

MyFirstCocosShooterGame

first shooter game for my cocos learning
Objective-C
1
star
42

Python

learn python from scratch
Python
1
star
43

BooksManage

Ruby
1
star
44

Html5

learn html5 from scratch
1
star
45

User-Login-Page

A user log-in page prototype written in Ruby on Rails based on the scaffold generator program
Ruby
1
star
46

VintJS

一款开发中前端富应用MVP框架。
JavaScript
1
star
47

sinatpy2.x

Python
1
star
48

GAE

google app engine
Python
1
star
49

miscdemo

Java
1
star