Reputation: 453
I have to use UIWebView
in my project and I seem that I got a problem.
Well I have html as below.
<html>
<a onclick="myFunction(1)">element1</a>
<a onclick="myFunction(2)">element1</a>
<a onclick="myFunction(3)">element1</a>
</html>
When I click to the a href link I have to execute my javascript code
<script>
var arr = [];
function myFunction(number) {
arr.push(number);
}
</script>
now how I can pass an Array
to UIViewController
?
and how I know in swift if I call myFunction()
from UIWebView
?
Upvotes: 1
Views: 1984
Reputation: 93141
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>
Upvotes: 3