WKWebViewJavascriptBridge

repository·master·Indexed 23 days ago

https://github.com/lision/wkwebviewjavascriptbridge

A lightweight, high-performance framework for bidirectional communication between iOS native code (Swift) and web content running in a WKWebView. It allows developers to register handlers and call functions across the native-to-JS and JS-to-native boundary. Supports iOS 9.0+ and Xcode 9.0+, with installation available via Swift Package Manager, CocoaPods, Carthage, or manual integration.

Tokens
1.7K
Snippets
2
Records
5
Agent score
30%

What's inside WKWebViewJavascriptBridge

  1. Install WKWebViewJavascriptBridge

    master

    You can install the framework using Swift Package Manager, CocoaPods, Carthage, or by manual integration.

    Swift Package Manager

    1. In Xcode, select File > Add Package Dependencies....
    2. Enter https://github.com/Lision/WKWebViewJavascriptBridge.git.
    3. Add the WKWebViewJavascriptBridge package to your app target.
    4. Add import WKWebViewJavascriptBridge to your Swift files.

    CocoaPods

    1. Add pod 'WKWebViewJavascriptBridge', '~> 1.2.0' to your Podfile.
    2. Run pod install or pod update.
    3. Add import WKWebViewJavascriptBridge to your Swift files.

    Carthage

    1. Add github "Lision/WKWebViewJavascriptBridge" ~> 1.2.0 to your Cartfile.
    2. Run carthage update --platform ios.
    3. Add the WKWebViewJavascriptBridge framework to your project.

    Manual Installation

    Clone the repository and manually add the files found in the WKWebViewJavascriptBridge directory to your project.

  2. Implement Native-to-JS and JS-to-Native communication

    master

    To use the bridge, follow these four steps to connect your Swift native code and JavaScript web code.

    1. Instantiate the bridge in Swift

    Initialize the bridge using your existing WKWebView instance:

    bridge = WKWebViewJavascriptBridge(webView: webView)

    2. Register Handlers in Native (Swift)

    Use register(handlerName:...) to listen for calls from JavaScript, and call(handlerName:...) to trigger a handler in JavaScript:

    // Listen for JS calls
    bridge.register(handlerName: "testiOSCallback") { (paramters, callback) in
        print("testiOSCallback called: \(String(describing: paramters))")
        callback?("Response from testiOSCallback")
    }
    
    // Call a JS handler
    bridge.call(handlerName: "testJavascriptHandler", data: ["foo": "before ready"], callback: nil)

    3. Setup the Bridge in JavaScript

    Copy and paste this helper function into your JavaScript code to initialize the connection:

    function setupWKWebViewJavascriptBridge(callback) {
        if (window.WKWebViewJavascriptBridge) { return callback(WKWebViewJavascriptBridge); }
        if (window.WKWVJBCallbacks) { return window.WKWVJBCallbacks.push(callback); }
        window.WKWVJBCallbacks = [callback];
        window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null)
    }

    4. Use the Bridge in JavaScript

    Call setupWKWebViewJavascriptBridge with a callback function. Inside that callback, you can use registerHandler to listen for native calls and callHandler to send messages to native code:

    setupWKWebViewJavascriptBridge(function(bridge) {
    	/* Initialize your app here */
    
    	// Listen for Native calls
    	bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
    		console.log('iOS called testJavascriptHandler with', data)
    		responseCallback({ 'Javascript Says':'Right back atcha!' })
    	})
    
    	// Call Native handlers
    	bridge.callHandler('testiOSCallback', {'foo': 'bar'}, function(response) {
    		console.log('JS got response', response)
    	})
    })
  3. Use WKWebViewJavascriptBridge in JavaScript

    master

    To use the bridge in your web application, follow these steps:

    1. Include the setup function: Copy and paste the setupWKWebViewJavascriptBridge function into your JavaScript code. This function handles the initialization and ensures the bridge is ready before your app logic runs.
    2. Initialize your app: Call setupWKWebViewJavascriptBridge and provide a callback function. The callback receives the bridge object.
    3. Register a handler: Use bridge.registerHandler(handlerName, callback) to listen for calls from Native.
    4. Call a Native handler: Use bridge.callHandler(handlerName, data, callback) to send messages to iOS.
    // 1. Setup function to be copied into your JS
    function setupWKWebViewJavascriptBridge(callback) {
        if (window.WKWebViewJavascriptBridge) { return callback(WKWebViewJavascriptBridge); }
        if (window.WKWVJBCallbacks) { return window.WKWVJBCallbacks.push(callback); }
        window.WKWVJBCallbacks = [callback];
        window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null)
    }
    
    // 2. Use the bridge
    setupWKWebViewJavascriptBridge(function(bridge) {
    
        /* Initialize your app here */
    
        // Register a handler to receive calls from Native
        bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
            console.log('iOS called testJavascriptHandler with', data)
            responseCallback({ 'Javascript Says':'Right back atcha!' })
        })
    
        // Call a Native handler
        bridge.callHandler('testiOSCallback', {'foo': 'bar'}, function(response) {
            console.log('JS got response', response)
        })
    })
  4. Use WKWebViewJavascriptBridge in Swift

    master

    To use the bridge in your native iOS code, follow these steps:

    1. Instantiate the bridge: Pass your existing WKWebView instance to the WKWebViewJavascriptBridge initializer.
    2. Register a handler: Use register(handlerName:handler:) to listen for calls coming from JavaScript. The handler provides parameters and a callback closure to send data back to JS.
    3. Call a JS handler: Use call(handlerName:data:callback:) to trigger a function in the web environment.
    // 1. Instantiate
    bridge = WKWebViewJavascriptBridge(webView: webView)
    
    // 2. Register a handler in Native
    bridge.register(handlerName: "testiOSCallback") { (parameters, callback) in
        print("testiOSCallback called: \(String(describing: parameters))")
        callback?("Response from testiOSCallback")
    }
    
    // 3. Call a JS handler from Native
    bridge.call(handlerName: "testJavascriptHandler", data: ["foo": "before ready"], callback: nil)