Simple Design for Java bridge with Javascript. Also can get javascript console.log.

Overview

language language language

SDBridgeKotlin is here.

If your h5 partner confused about how to deal with iOS and Android. This Demo maybe help.

最常见的问题. WebViewJavascriptBridge is not defined 的处理方案.

是js或者ts在使用的时候,WebViewJavascriptBridge对象还没有挂载到window上 ,让js或者ts自己挂载!!!

具体的js或者ts如何做可以看这个视频.

视频接入教程和常见问题都在这里(遇到问题一定要看哦 😯 .

YouTube video is here.

Usage

JitPack.io

I strongly recommend https://jitpack.io

repositories {
    ...
    maven { url 'https://jitpack.io' }
}
dependencies {
    implementation 'com.github.SDBridge:SDBridgeJava:1.0.4'
}
  1. Instantiate bridge with a WebView in Java:
  private void setupView() {
          WebView webview = findViewById(R.id.webView);
          setAllowUniversalAccessFromFileURLs(webview);
          Button buttonSync = findViewById(R.id.buttonSync);
          Button buttonAsync = findViewById(R.id.buttonAsync);
          buttonSync.setOnClickListener(this);
          buttonAsync.setOnClickListener(this);

          bridge = new WebViewJavascriptBridge(this,webview);
          bridge.consolePipe(string -> {
              System.out.println("333333333");
              System.out.println(string);
          });
          bridge.register("DeviceLoadJavascriptSuccess", (map, callback) -> {
              System.out.println("Next line is javascript data->>>");
              System.out.println(map);
              HashMap<String,String> result = new HashMap<>();
              result.put("result","Android");
              callback.call(result);
          });
          webview.setWebViewClient(new WebViewClient(){
              @Override
              public boolean shouldOverrideUrlLoading(WebView view, String url) {
                  Log.d(TAG,"shouldOverrideUrlLoading");
                  view.loadUrl(url);
                  return true;
              }
              @Override
              public void onPageStarted(WebView view, String url, Bitmap favicon) {
                  Log.d(TAG,"onPageStarted");
                  bridge.injectJavascript();
              }
              @Override
              public void onPageFinished(WebView view, String url) {
                  Log.d(TAG,"onPageFinished");
              }
          });
          // Loading html in local ,This way maybe meet cross domain. So You should not forget to set
          // /*...setAllowUniversalAccessFromFileURLs... */
          // If you loading remote web server,That can be ignored.
          webview.loadUrl("file:///android_asset/Demo.html");
      }
  1. In Java, and call a Javascript Sync/Async function:
 @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button2) {
            HashMap<String, String> data = new HashMap<>();
            data.put("AndroidKey","AndroidValue");
            //Call Javascript Sync function 
            bridge.call("GetToken", data, map -> {
                System.out.println("Next line is javascript data->>>");
                System.out.println(map);
            });
        }else if(view.getId() == R.id.button3){
            HashMap<String, String> data = new HashMap<>();
            data.put("AndroidKey","AndroidValue");
            ///Call Javascript Async function 
            bridge.call("AsyncCall", data, map -> {
                System.out.println("Next line is javascript data->>>");
                System.out.println(map);
            });
        }
    }
  1. In javascript file or typescript and html file like :
<div id="SDBridge"> web content </div>
<script>
    // Give webview 1.5s to load other javascript files.
    setTimeout(()=>{
        console.log("Demo222222222222222222");
        const bridge = window.WebViewJavascriptBridge;
        // JS tries to call the native method to judge whether it has been loaded successfully and let itself know whether its user is in android app or IOS app
        bridge.callHandler('DeviceLoadJavascriptSuccess', {key: 'JSValue'}, function(response) {
            let result = response.result
            if (result === "iOS") {
            console.log("Javascript was loaded by IOS and successfully loaded.");
            document.getElementById("SDBridge").innerText = "Javascript was loaded by IOS and successfully loaded.";
            window.iOSLoadJSSuccess = true;
           } else if (result === "Android") {
            console.log("Javascript was loaded by Android and successfully loaded.");
            document.getElementById("SDBridge").innerText = "Javascript was loaded by Android and successfully loaded.";
            window.AndroidLoadJSSuccess = true;
           }
        });
        // JS register method is called by native
        bridge.registerHandler('GetToken', function(data, responseCallback) {
            console.log(data);
            document.getElementById("SDBridge").innerText = "JS get native data:" + JSON.stringify(data);
            let result = {token: "I am javascript's token"}
            //JS gets the data and returns it to the native
            responseCallback(result)
        });
        bridge.registerHandler('AsyncCall', function(data, responseCallback) {
            console.log(data);
            document.getElementById("SDBridge").innerText = "JS get native data:" + JSON.stringify(data);
            //Call await function must with  (async () => {})();
            (async () => {
            const callback = await generatorLogNumber(1);
            let result = {token: callback};
            responseCallback(result);
            })();
         });
        function generatorLogNumber(n){
            return new Promise(res => {
            setTimeout(() => {
             res("Javascript async/await callback Ok");
                 }, 1000);
            })
       }
},1500);

</script>

Global support for free

WhatsApp: SDBridgeJava Support

Telegram: SDBridgeJava Support

WeChat :

Email: [email protected]

History version update ?

v1.0.3

1.Java can get console.log Multi parameter.

v1.0.4

1.Optimized coding.

License

SDBridgeSwift is released under the MIT license. See LICENSE for details.

You might also like...

Simple springboot API for addressBook. Supports all REST controllers and have custom error handling for every specific case, also supports redis caching.

Simple springboot API for addressBook. Supports all REST controllers and have custom error handling for every specific case, also supports redis caching.

AddressBook-SpringBoot-API Simple Springboot API for addressBook with redis cache. Supports all REST controllers and have custom error handling for ev

Jan 21, 2022

A plugin that running in powernukkit and can run javascript in commandblock

A plugin that running in powernukkit and can run javascript in commandblock

A plugin that running in powernukkit and can run javascript in commandblock

Aug 4, 2022

Shitty, yet simple way to get someone's token right at their discord client's startup.

discord-token-stealer Shitty, yet simple discord injector to add a little spice to their discord client Disclaimer: This is for educational purposes o

Sep 26, 2022

A simple tool to get method stack

A simple tool to get method stack

Jan 17, 2022

Simple examples for various Design patterns

About Simple examples for various Design patterns. Design patterns represent the best practices used by experienced object-oriented software developer

Jan 26, 2022

a simple News App styled by Material Design

Material News Material Design 风格的 Android 新闻 App 1 代码结构 /app/src/main/ 1.1 Java代码部分 ./java/com/java/shanjingbo/ activity/:程序入口 Activity adapter/:Recyc

Sep 13, 2021

SimpleIcons4J is a Java implementation of the simple-icons JavaScript library

SimpleIcons4J SimpleIcons4J is a Java implementation of the simple-icons JavaScript library and is inspired by simpleicons.org. This library currently

Apr 9, 2022

Community extension to generate a Java client from the provided Camunda 7 OpenAPI descitpion and also warp it into Spring Boot

Camunda Engine OpenAPI REST Client Java and Spring Boot This community extension is a convenience wrapper around the generated Java client from the Ca

Dec 28, 2022

Java related projects and also a begginer level projects

Java related projects and also a begginer level projects

Dec 15, 2022
Owner
null
Java-Trading-Log-Project - A Trading Log to Journal Your Trades.

Abhi's Project - Trading Log Trading Background I am very passionate about trading. I have been studying the financial markets for a few years and hav

Abhigyan Dabla 0 Jul 18, 2022
Welcome to the EHS robotics club's GitHub repository, this will also be used as our primary community center and means of communication. Also be sure to join our remind for on the go updates @EHSFTC21

NOTICE This repository contains the public FTC SDK for the Ultimate Goal (2020-2021) competition season. Formerly this software project was hosted her

null 5 Feb 25, 2022
Curated Collection of all Low level design Questions and implementation asked in major Tech companies , Get yourself prepared for the LLD round and ace the interview.

Low level Design / Machine Coding Question Collections What is Machine Coding Round ? Machine Coding Round has become very popular interview round in

Kumaran gowthaman 619 Dec 31, 2022
An Android library for member secretGFX group, This can be used to growing your apps and get more install via a simple banner view & native view and interstitial dialog.

GFX-AdPromote An Android library for member secretGFX group, This can be used to growing your apps and get more install via a simple banner view & nat

SAID MOTYA 10 Dec 25, 2022
This project was created as a simple example to show how we can implement the hexagonal architecture(software design) proposed by Netflix.

Netflix Hexagonal Architecture Table of contents About the project Description Built with Installation Requirements to run Usage information Run Licen

José Lucas 12 Dec 20, 2022
This project uses the artificial potential field method to realize the path planning of the robot, and completes the trajectory optimization through other settings. It can also be combined with laser SLAM, target recognition and other technologies for path planning.

FRCAutoDriver 项目说明 Project Instruction 本项目利用人工势场法,实现机器人的路径规划,并通过其他设置完成轨迹优化,还可以结合激光SLAM、目标识别等技术进行路径规划 This project uses the artificial potential field

ZhangzrJerry 2 Sep 9, 2022
Stetho is a debug bridge for Android applications, enabling the powerful Chrome Developer Tools and much more.

Stetho Stetho is a sophisticated debug bridge for Android applications. When enabled, developers have access to the Chrome Developer Tools feature nat

Meta 12.6k Jan 3, 2023
Literally just adds milk, to act as a bridge for any other mods that want to do the same.

Milk lib Literally just adds milk, to act as a bridge for any other mods that want to do the same. See the Milk class for customisation; It allows for

null 5 Oct 17, 2022
Velocity global chat/discord bridge

VelocityDiscord Velocity global chat/discord bridge Default config generated on startup: # Don't change this config_version="1" [discord] # Bot token

Foo 8 Dec 18, 2022
GodType is a very simple Bukkit plugin to allow the console (or a player) to chat as a defined name.

GodType GodType is a very simple Bukkit plugin to allow the console (or a player) to chat as a defined name. Config A config.yml file will be created

null 1 Dec 24, 2021