Coder Social home page Coder Social logo

eroscai / szwebviewbridge Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 152 KB

Swift WebView bridge. Based on message handler.

License: MIT License

Ruby 5.08% Swift 76.75% HTML 7.31% JavaScript 10.87%
swift wkwebview bridge message handler webkit webview message-handler callback

szwebviewbridge's Introduction

SZWebViewBridge

CI Status Version License Platform

SZWebViewBridge is a lightweight, pure-Swift library for sending messages between WKWebView and Web client. Based on message handler.

Requirements

  • iOS 10.0+
  • Swift 5.0+

Installation

SZWebViewBridge is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'SZWebViewBridge'

Principle

  1. Encapsulates the JS code and Native code for comunication, and automatically inject JS code when initializing the Bridge on the Native side, without any additional configuration.

Below is the sample code for sending a message on the JS side:

// post message with params
function testAlert() {
    window.szBridge.post('alert', {
        'title': 'This is alert title',
        'message': 'This is alert message'
})
}

// post message with params and callback
function testReceiveSuccess() {
    window.szBridge.post('testSuccess', {
        'key1': 'value1',
        'key2': {
            'subkey1': 'subvalue2'
        }
    }, function (result, error) {
        alertUsingBridge(JSON.stringify(result))
    })
}

The sample code for Native side:

// post message
webViewBridge.post(action: "change", params: nil)

// callback
let response = [
    "param1": "value1",
    "param2": "value2",
]
let success: SZWebViewBridgeResult = .success(response)
webViewBridge.callback(callbackId: callbackId, result: success)
  1. Native side need Handler to receive message sent by JS side. The passed parameters will be automatically parsed into the params variable, and other useful parameters also defined in the Handler. For full list of avaiable parameters, refer to SZWebViewBridgeBaseHandler.

Below is the sample code for receive a message and sends a callback.

import UIKit
import SZWebViewBridge

class TestReceiveSuccessHandler: SZWebViewBridgeBaseHandler {

    override func invoke() throws {
        guard let params = params else { return }

        print(params)
        if let webViewBridge = webViewBridge {
            if isValidCallbackId {
                let response = [
                    "param1": "value1",
                    "param2": "value2",
                ]
                let success: SZWebViewBridgeResult = .success(response)
                webViewBridge.callback(callbackId: callbackId, result: success)
            }
        }

    }
    
}
  1. Because all handlers must adopt the same protocol, it can be easily get parameters and various variables needed.
  2. Each handler is a separate class/file that can be easily added and removed.

Usage

  1. Init SZWebViewBridge with a WKWebView and UIViewController. (The UIViewController will assign to handler and would be used in the future.(e.g., push or present to another UIViewController))
let bridge = SZWebViewBridge(webView: webView, viewController: self)
webViewBridge = bridge  // make sure bridge will not be deinit.
  1. Add some predefined handlers. For example define a TitleHandler
import UIKit
import SZWebViewBridge

class TitleHandler: SZWebViewBridgeBaseHandler {

    override func invoke() throws {
        guard let params = params else { return }

        if let title = params["title"] as? String {
            if let viewController = viewController {
                viewController.title = title
            }
        }
    }

}

Then use function addHandlers or removeHandlers to add/remove handlers.

var handlers: SZWebViewBridgeBaseHandlerObject {
    return [
        "setTitle": TitleHandler.self,
        ...
    ]
}
webViewBridge.addHandlers(handlers: handlers)
  1. All Done! More detail usage please check example project.

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Author

eroscai, [email protected]

License

SZWebViewBridge is available under the MIT license. See the LICENSE file for more info.

szwebviewbridge's People

Contributors

eroscai avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.