Giter Site home page Giter Site logo

lision / wkwebviewjavascriptbridge Goto Github PK

View Code? Open in Web Editor NEW
1.2K 29.0 139.0 481 KB

🌉 A Bridge for Sending Messages between Swift and JavaScript in WKWebViews.

License: MIT License

Objective-C 2.41% Swift 85.22% HTML 9.48% Ruby 2.89%
swift javascript bridge wkwebviewjavascriptbridge wkwebview webkit hybrid js jsbridge webviewjavascriptbridge

wkwebviewjavascriptbridge's Introduction

language  Carthage compatible  License MIT  Support  CocoaPods  Build Status  CocoaPods

中文介绍

This project is inspired by WebViewJavascriptBridge!

What Can WKWebViewJavascriptBridge Do?

You can write hybrid modules in just a few lines of code by using WKWebViewJavascriptBridge without the need to be concerned with the underlying messaging implementation.

Why Only Support WKWebView?

Advantages of WKWebView

It is well known that WKWebView loads web pages faster and more efficiently than UIWebView, and also doesn't have as much memory overhead for you.

Under the current timeline, most iOS apps only support iOS 9.0+.

UIWebView Cross-Domain Access Vulnerability

The reason for the iOS platform cross-domain access vulnerability is due to UIWebView turning on the WebKitAllowUniversalAccessFromFileURLs and WebKitAllowFileAccessFromFileURLs options.

WKWebView default allowFileAccessFromFileURLs and allowUniversalAccessFromFileURLs option is false.

Features

  • Swift Support: Swift 3.2 ~ 5 Support.
  • High Performance: The messaging performance is higher than intercept requests.
  • High Speed: No need to consider alert box safety timeout.
  • Lightweight: This framework contains only 3 files.
  • Non-intrusive: There is no need to make the webview class inherit from other base class.

Usage

1. Instantiate WKWebViewJavascriptBridge with a WKWebView:

bridge = WKWebViewJavascriptBridge(webView: webView)

2. Register a Handler in Native, and Call a JS Handler:

bridge.register(handlerName: "testiOSCallback") { (parameters, callback) in
    print("testiOSCallback called: \(String(describing: parameters))")
    callback?("Response from testiOSCallback")
}

bridge.call(handlerName: "testJavascriptHandler", data: ["foo": "before ready"], callback: nil)

3. Copy and Paste setupWKWebViewJavascriptBridge 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)
}

4. Finally, Call setupWKWebViewJavascriptBridge and then Use The Bridge to Register Handlers and Call Native Handlers:

setupWKWebViewJavascriptBridge(function(bridge) {

	/* Initialize your app here */

	bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
		console.log('iOS called testJavascriptHandler with', data)
		responseCallback({ 'Javascript Says':'Right back atcha!' })
	})

	bridge.callHandler('testiOSCallback', {'foo': 'bar'}, function(response) {
		console.log('JS got response', response)
	})
})

Installation

Cocoapods

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

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.

Manually

Either clone the repo and manually add the Files in WKWebViewJavascriptBridge.

Requirements

This framework requires iOS 9.0+ and Xcode 9.0+.

Contact

License

WKWebViewJavascriptBridge is provided under the MIT license. See LICENSE file for details.

wkwebviewjavascriptbridge's People

Contributors

cdoky avatar codingbot000 avatar lision avatar raid5 avatar thomersch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wkwebviewjavascriptbridge's Issues

Carthage build error

Hey, I'm getting this error when trying to add this project using carthage:

*** Skipped building WKWebViewJavascriptBridge due to the error:
Dependency "WKWebViewJavascriptBridge" has no shared framework schemes for any of the platforms: iOS

NSInternalInconsistencyException

I got Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[Webview.WebViewController webView:decidePolicyForNavigationAction:decisionHandler:] was called more than once

swift initializer is inaccessible due to 'private' protection level

Hi, using swift 4.2 i got this error on the WKWebViewJavascriptBridge extension in WKWebViewJavascriptBridge.swift file:
swift initializer is inaccessible due to 'private' protection level

The error is caused by "webview" in line 83, "base" in line 90 and "flushMessageQueue()" in line 94.
The problem is that it can't access these properties/methods beacause they are private..

NoHandlerException, No handler for message from JS

Sometime I get this error. Could you plz explain in which case we get this error?.
Because this issue does not have any callback, so front-end just wait here forever, do we need a callback/event/delegate for this thing?

BR

Xcode15 Support

Hi @Lision
Currently, the podspec specify the deployment target to iOS 9.0.

For other Cocoapods libraries, if you have WKWebViewJavascriptBridge as a dependency pod, your library will not lint correctly your podspec using Xcode 15 and up.
May I request to update the Podspec / Update the Swift version.

Alternatively I can raise a pr as well. Would you be willing to review and merge.

P.S. I am more than willing to do the honour for releasing a new version post merge if you add me as a contributor. And help maintain going forward.

Thanks

关于 WKWebViewJavascriptBridge 的实现方式有一点疑问

你好

我看了下源码,发现从jsnative发送消息的部分的实现是采用了之前在UIWebView上使用Bridge的方式:是在js中保存sendMessageQueue变量,然后在native中调用_fetchQueue()的方式来实现的。

这里有一点疑问,WKWebView提供了WKScriptMessageHandler,可以通过代理拿到WKScriptMessage,而这个对象中包含了由js发送的消息,为什么不采用这种方式呢。

if !startupMessageQueue.isEmpty

Hi, I'm probably missing something, but in the case that !startupMessageQueue.isEmpty, you append to startupMessageQueue but then I miss where that message gets picked up and dispatched eventually.

    private func queue(message: Message) {
        if startupMessageQueue.isEmpty {
            dispatch(message: message)
        } else {
            startupMessageQueue.append(message)
        }
    }

Add a git tag to simplify SPM integration process

Since there is no tag for #37, the only way to integrate this package with SPM is to pin a specific commit hash.

Adding a tag would make this better so that we can use a semantic version in the SPM integration.

image

I'd like to help with that, but I'm afraid that there is no way to make a pull request for just add a tag 😅, at least for now.

当二次创建web时,报错

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to add script message handler with name 'iOS_Native_InjectJavascript' when one already exists.'

What If I am calling button using JS onClick event? How to handle that?

What If I am calling button using JS onClick event? How to handle that? Can u guide me?

`

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">

<title>XYZ</title>

<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">

<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">

<!-- Material Design Bootstrap -->
<link href="css/mdb.min.css" rel="stylesheet">

<!-- Template styles -->
<style rel="stylesheet">
    /* TEMPLATE STYLES */

    main {
        margin-top: 3rem;
    }

    main .card {
        margin-bottom: 2rem;
    }

    @media only screen and (max-width: 768px) {
        .read-more {
            text-align: center;
        }
    }
</style>
<main>
    <!--Main layout-->
    <div class="container">

        <!--Second row-->
        <div class="row">

            <div class="col-md-16">
                <div class="card">
                    <div class="card-block">
                        <h4 class="card-title">Play Music</h4>
                        <div class="read-more">
                            <a id="sound" class="btn btn-primary" onClick="playSound()">Play</a>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        </div>
        <!--/.Second row-->
        <hr>

    </div>
    <!--/.Main layout-->
</main>

<!-- SCRIPTS -->

<!-- JQuery -->
<script type="text/javascript" src="js/jquery-2.2.3.min.js"></script>

<!-- Bootstrap tooltips -->
<script type="text/javascript" src="js/tether.min.js"></script>

<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="js/bootstrap.min.js"></script>

<!-- MDB core JavaScript -->
<script type="text/javascript" src="js/mdb.min.js"></script>

<script type="text/javascript" src="js/script.js"></script>

<script type="text/javascript">

    function playSound() {
        bridge.callHandler('play_sound', {"name": "www/1.mp3"}, function(response) {
        log('JS got response', response, 'js')
        })

    }

</script>

<script type="text/javascript">
    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)
    }

setupWKWebViewJavascriptBridge(function(bridge) {

                               
                               })
</script>
`

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.