qcliwei / SDBridgeKotlin

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

language language language language

SDBridgeJava 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: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>

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.

About

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

License:MIT License


Languages

Language:Kotlin 64.7%Language:JavaScript 21.2%Language:HTML 14.1%