Skip to content

Instantly share code, notes, and snippets.

@wayne5540
Created January 20, 2017 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wayne5540/59f7efd00f76dc91eeb383f8b4128c7e to your computer and use it in GitHub Desktop.
Save wayne5540/59f7efd00f76dc91eeb383f8b4128c7e to your computer and use it in GitHub Desktop.
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
let contentController = WKUserContentController()
// Inject JavaScript which sending message to App
let js: String = "window.webkit.messageHandlers.callbackHandler.postMessage('Hello from JavaScript');"
let userScript = WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
contentController.removeAllUserScripts()
contentController.addUserScript(userScript)
// Add ScriptMessageHandler
contentController.add(
self,
name: "callbackHandler"
)
webConfiguration.userContentController = contentController
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "http://localhost:3000")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
// Implement `WKScriptMessageHandler`,handle message which been sent by JavaScript
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if(message.name == "callbackHandler") {
print("JavaScript is sending a message \(message.body)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment