You can use WKWebView, available since OS X 10.10 or iOS 8 to do the job. In Xcode 9 and later, you can add the WkWebView directly to Interface Builder and connect the IBOutlet. For earlier versions of Xcode, you must do so programmatically. For full compatibility, the code below shows how to add the WKWebView programmatically.
Make your view controller conform to the WKScriptMessageHandler protocol and add the following code:
class ViewController: UIViewController, WKScriptMessageHandler {
weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// myAction is the pipe name Javascript uses to post messages
// to your app. You can define more than 1 pipe.
let controller = WKUserContentController()
controller.addScriptMessageHandler(self, name: "myAction")
let config = WKWebViewConfiguration()
config.userContentController = controller
// Add the WKWebView to the view
let frame = CGRectMake(20, 20, 200, 200)
let webView = WKWebView(frame: frame, configuration: config)
self.view.addSubview(webView)
// Load your HTML file
let url = NSBundle.mainBundle().URLForResource("mydoc", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessToURL: url)
// Pass reference to the view controller
self.webView = webView
}
// Handle the message posted by Javascript
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let arr = message.body as? [Int] {
print(arr)
}
}
}
And the HTML + Javascript:
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Hello world</title>
<script type="text/javascript">
var arr = [];
function myFunction(number) {
arr.push(number);
// Send a message to your app on the myAction pipe
window.webkit.messageHandlers.myAction.postMessage(arr);
}
</script>
</head>
<body>
<a href="javascript:void(0)" onclick="myFunction(1)">element1</a>
<a href="javascript:void(0)" onclick="myFunction(2)">element2</a>
<a href="javascript:void(0)" onclick="myFunction(3)">element3</a>
</body>
</html>
WKWebView