Skip to content

🍉An iOS bridge for sending messages between Swift and JavaScript in WKWebView

License

Notifications You must be signed in to change notification settings

Xiaoye220/JSBridge

Repository files navigation

JustBridge

pod iOS lisence swift

An iOS bridge for sending messages between Swift and JavaScript in WKWebView

ScreenShot

Screenshots

CocoaPods

use_frameworks!
pod 'JustBridge', '~> 4.2.0'

Usage

JustBridge is easy to use. Just init a bridge and then register handler or call handler.

  1. import JustBridge and declare an ivar property:
import JustBridge

...

var bridge: JustBridge!
  1. Instantiate JustBridge with a WKWebView:
bridge = JustBridge(with: webView)
  1. Register a handler in Swift, and call a JavaScript handler

    • the errorMessage can be HandlerNotExistError or DataIsInvalidError , type of errorMessage is String

    • callback and errorCallback can be nil

bridge.register("swiftHandler") { (data, callback) in
    print("[js call swift] - data: \(data ?? "nil")\n")
    callback("[response from swift] - response data: I'm swift response data")
}

bridge.call("jsHandler", data: data, callback: { responseData in
    print(responseData ?? "have no response data")
}, errorCallback: { errorMessage in
    print(errorMessage)
})
  1. Register a handler in JavaScript, and call a Swift handler
    • the errorMessage can only be HandlerNotExistError , type of errorMessage is String
    • callback and errorCallback can be null
window.bridge.register("jsHandler", function(data, callback) {
    console.log("[swift call js] - data: " + JSON.stringify(data));
    callback("[response from js] - response data: I'm js response data");
});

window.bridge.call("swiftHandler", "hello world from js", function(responseData) {
    console.log(responseData.toString())
}, function(errorMessage) {
    console.log("error: " + errorMessage)
});

Excample

You can clone or download this project for more details.

About

🍉An iOS bridge for sending messages between Swift and JavaScript in WKWebView

Resources

License

Stars

Watchers

Forks

Packages

No packages published