18 Unstar Star 51 Fork 13

chengfei.heng / SwiftJS

Create your Gitee Account
Explore and code with more than 5 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Without author's permission, this code is only for learning and cannot be used for other purposes.
Clone or download
Cancel
Notice: Creating folder will generate an empty file .keep, because not support in Git
Loading...
README.md

SwiftJS是用swift写的,用于演示如何和JavaScript进行交互的Demo.

效果

Features

  • JavaScript call Native App
  • Native App call JavaScript

Requirements

  • iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 7.2+

Communication

Usage

Native App 调用 H5中的JavaScript

let conf = WKWebViewConfiguration()
let userScript = WKUserScript(source: "redHeader()", injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
conf.userContentController.addUserScript(userScript)
webView = WKWebView(frame: self.view.frame, configuration: conf)

JavaScript 调用 Native App

1.首先添加一个WKScriptMessageHandler代理

class ViewController: UIViewController, WKScriptMessageHandler

2.实现«userContentController»的代理方法

func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!) {
    if(message.name == "callbackHandler") {
        println("JavaScript is sending a message \(message.body)")
    }
}

3.WebView启动对JavaScript的监听事件

contentController.addScriptMessageHandler(
    self,
    name: "callbackHandler" 
)

4.H5中,添加如下JavaScript

webkit.messageHandlers.callbackHandler.postMessage("I Love you");

Comments ( 1 )

Sign in for post a comment

About

Swift和JavaScript交互 spread retract
Cancel

Releases

No release

Gitee Metrics

Contributors

All

Activities

load more
can not load any more
Swift
1
https://gitee.com/chengfeisoft/SwiftJS.git
git@gitee.com:chengfeisoft/SwiftJS.git
chengfeisoft
SwiftJS
SwiftJS
master

Search