Skip to content

Instantly share code, notes, and snippets.

@seanbehan
Last active April 29, 2018 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanbehan/457a23628fc74af31f6e458d15d2e9ac to your computer and use it in GitHub Desktop.
Save seanbehan/457a23628fc74af31f6e458d15d2e9ac to your computer and use it in GitHub Desktop.
All the code you need for js/native bridge w/ html apps for android and ios (manifest and interface builder files excluded)
<html>
<button id='button'>Say Hi</button>
<script>
button = document.getElementById('button')
button.onclick = function(){
// if ios
// window.webkit.messageHandlers["scriptHandler"].postMessage("Hi")
//
// if android
// AndroidInterface.sayHi()
}
function sayHi(){
document.write("Hi")
}
</script>
</html>
package com.package.name
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import android.webkit.JavascriptInterface
import android.content.Context
class WebViewJsInterface(private val context: Context, private val webView: WebView) {
@JavascriptInterface
fun sayHi() {
webView.post { webView.loadUrl("javascript:sayHi()") }
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val webView = findViewById(R.id.webview) as WebView
webView?.settings?.javaScriptEnabled = true
webView.loadUrl("file:///android_asset/www/index.html")
webView.addJavascriptInterface( WebViewJsInterface(this, webView), "AndroidInterface");
}
}
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView?.configuration.userContentController.add(self, name: "scriptHandler")
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
if let url = Bundle.main.url(forResource: "www/index", withExtension: "html") {
webView.load(URLRequest(url: url))
}
}
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
webView.evaluateJavaScript("javascript:sayHi()")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment