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

Overview

language language language language

SDBridgeJava is here.

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

bilibili video introduction is here.

YouTube video is here.

Usage

JitPack.io

I strongly recommend https://jitpack.io

repositories {
    ...
    maven { url 'https://jitpack.io' }
}
dependencies {
    implementation 'com.github.SDBridge:SDBridgeKotlin:1.0.3'
}
  1. Instantiate bridge with a WebView in Kotlin:
  @SuppressLint("SetJavaScriptEnabled")
    private fun setupView(){
        val buttonSync = findViewById<Button>(R.id.buttonSync)
        val buttonAsync = findViewById<Button>(R.id.buttonAsync)
        mWebView = findViewById(R.id.webView)
        setAllowUniversalAccessFromFileURLs(mWebView!!)
        buttonSync.setOnClickListener(this)
        buttonAsync.setOnClickListener(this)
        bridge = WebViewJavascriptBridge(_context = this,_webView = mWebView )

        bridge?.consolePipe = object : ConsolePipe {
            override fun post(string : String){
                println("33333")
                println(string)
            }
        }
        bridge?.register("DeviceLoadJavascriptSuccess",object : Handler {
            override fun handler(map: HashMap<String, Any>?, callback: Callback) {
                println("Next line is javascript data->>>")
//                println(map)
                val result = HashMap<String, Any>()
                result["result"] = "Android"
                callback.call(result)
            }
        })
        mWebView!!.webViewClient = webClient
        // 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.
        mWebView!!.loadUrl("file:///android_asset/Demo.html")

    }

    private val webClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            println("shouldOverrideUrlLoading")
            return false
        }
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            println("onPageStarted")
            bridge?.injectJavascript()
        }
        override fun onPageFinished(view: WebView?, url: String?) {
            println("onPageFinished")
        }
    }
  1. In Kotlin, and call a Javascript Sync/Async function:
  override fun onClick(v: View?){
        when(v?.id){
            R.id.buttonSync -> {
                val data = java.util.HashMap<String, Any>()
                data["AndroidKey00"] = "AndroidValue00"
                //call js Sync function
                bridge?.call("GetToken", data, object : Callback {
                    override fun call(map: HashMap<String, Any>?){
                        println("Next line is javascript data->>>")
                        println(map)
                    }
                })
            }
            R.id.buttonAsync ->{
                val data = java.util.HashMap<String, Any>()
                data["AndroidKey01"] = "AndroidValue01"
                //call js Async function
                bridge?.call("AsyncCall", data, object : Callback {
                    override fun call(map: HashMap<String, Any>?){
                        println("Next line is javascript data->>>")
                        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("Javascript: Hello World.");
        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: SDBridgeKotlin Support

Telegram: SDBridgeKotlin Support

WeChat Group:

Email: [email protected]

History version update ?

v1.0.1

1.Kotlin can get console.log Multi parameter.

v1.0.2

1.Optimized coding.

v1.0.3

1.Optimized coding.

License

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

You might also like...
KaMP Kit by Touchlab is a collection of code and tools designed to get your mobile team started quickly with Kotlin Multiplatform.
KaMP Kit by Touchlab is a collection of code and tools designed to get your mobile team started quickly with Kotlin Multiplatform.

KaMP Kit Welcome to the KaMP Kit! About Goal The goal of the KaMP Kit is to facilitate your evaluation of Kotlin Multiplatform (aka KMP). It is a coll

A set of highly-opinionated, batteries-included gradle plugins to get you started building delicious multi-module Kotlin projects

Sourdough Gradle What is Sourdough Gradle? Sourdough is a set of highly opinionated gradle plugins that aim to act as the starter for your Kotlin proj

Events Calendar is a user-friendly library that helps you achieve a cool Calendar UI with events mapping. You can customise every pixel of the calendar as per your wish and still achieve in implementing all the functionalities of the native android calendar in addition with adding dots to the calendar which represents the presence of an event on the respective dates. It can be done easily, you are just a few steps away from implementing your own badass looking Calendar for your very own project! 🛠️ The missing drawable toolbox for Android. Create drawables programmatically and get rid of the boring and always repeated drawable.xml files.
🛠️ The missing drawable toolbox for Android. Create drawables programmatically and get rid of the boring and always repeated drawable.xml files.

DrawableToolbox English | 中文 The missing DrawableToolbox for Android. Create drawables programmatically and get rid of the boring and always repeated

[Android Library] Get easy access to device information super fast, real quick
[Android Library] Get easy access to device information super fast, real quick

DeviceInfo-Sample Simple, single class wrapper to get device information from an android device. This library provides an easy way to access all the d

It's finally easy to take photos/videos via camera or get photos/videos from gallery on Android.
It's finally easy to take photos/videos via camera or get photos/videos from gallery on Android.

Shutter-Android It's finally easy to take photos/videos via camera or get photos/videos from gallery on Android. What is Shutter? Shutter is an Androi

Example mod with Mixin to help you to get started with creating a mod with mixins.

ExampleMixinMod Example mod with Mixin to help you to get started with creating a mod with mixins. For usage of mixins, see here. Also, remember to tu

An application I am following in a Udemy course to get experience developing an e-commerce using PayPal and Mercado Libre Pago
An application I am following in a Udemy course to get experience developing an e-commerce using PayPal and Mercado Libre Pago

🏪 E-Commerce 🗂 Table of Contents General Infomation Technologies Used Features

Flutter plugin that leverages Storage Access Framework (SAF) API to get access and perform the operations on files and folders
Flutter plugin that leverages Storage Access Framework (SAF) API to get access and perform the operations on files and folders

Flutter plugin that leverages Storage Access Framework (SAF) API to get access and perform the operations on files and folders.

Owner
null
An experimental tool for building console UI in Kotlin using the Jetpack Compose compiler/runtime

An experimental tool for building console UI in Kotlin using the Jetpack Compose compiler/runtime

Jake Wharton 1.4k Dec 28, 2022
An android application for creating a journal for subjects you studied and also you can set timer for break.

Study Journal An android application for creating a journal for subjects you studied and also you can set timer for break between two consecutive subj

Prasoon 3 Aug 10, 2022
With Viola android face detection library, you can detect faces in a bitmap, crop faces using predefined algorithm and get additional information from the detected faces.

Viola Viola android face detection library detects faces automatically from a bitmap, crop faces using the predefined algorithms, and provides supplem

Darwin Francis 58 Nov 1, 2022
JavaScript evaluation from kotlin common code for android & iOS

Mobile Kotlin javascript This is a Kotlin MultiPlatform library that allows you to run JavaScript code from common Kotlin code Table of Contents Featu

IceRock Development 14 Aug 29, 2022
Lambda-snake.kt - Snake Game Implementation for Web using Kotlin programming language compiled for Javascript

Projeto da disciplina de Linguagem de Programação Funcional 2021.1 (jan/2022) ??

Alex Candido 3 Jan 10, 2022
🚀 Native iOS- and Android- Apps with JavaScript

Titanium Welcome to the Titanium open source project. Titanium provides a mature platform for developers to build completely native cross-platform mob

Team Appcelerator 2.6k Jan 4, 2023
Uproot-JS - Extract JavaScript files from burp suite project with ease

Extract JavaScript files from burp suite project with ease. Disclaimer I am not

Dexter0us 50 Aug 8, 2022
A template that utilizes both Scala and Kotlin because why not (And also because I endorse programming hell)

Fabric-Scala-Kotlin-template A template that utilizes both Scala and Kotlin because why not (And also because I endorse programming hell) I don't care

null 1 Dec 25, 2021
WordMasterKMP - WIP Kotlin Multiplatform sample inspired by Wordle and also Word Master web sample

WordMasterKMP WIP Kotlin Multiplatform sample inspired by Wordle and also Word M

John O'Reilly 56 Oct 4, 2022
Simple MVVM app to get photos through https://unsplash.com api

MyPhotoLoaderApp Simple photo loading app powered by Unsplash.com which implements MVVM architecture using Hilt, Navigation Component, Retrofit, Pagin

Behnam Banaei 10 Oct 6, 2022