我必须在我的项目中使用 UIWebView
,我似乎遇到了问题。
好吧,我有如下 html。
<html>
<a onclick="myFunction(1)">element1</a>
<a onclick="myFunction(2)">element1</a>
<a onclick="myFunction(3)">element1</a>
</html>
当我点击 href 链接时,我必须执行我的 javascript 代码
<script>
var arr = [];
function myFunction(number) {
arr.push(number);
}
</script>
现在如何将 Array
传递给 UIViewController
?
如果我从 UIWebView
调用 myFunction()
,我如何快速知道?
最佳答案
您可以使用自 OS X 10.10 或 iOS 8 起可用的 WKWebView
来完成这项工作。在 Xcode 9 及更高版本中,您可以将 WkWebView
直接添加到 Interface Builder 并连接 IBOutlet
。对于较早版本的 Xcode,您必须以编程方式执行此操作。为了完全兼容,下面的代码显示了如何以编程方式添加 WKWebView
。
使您的 View Controller 符合WKScriptMessageHandler
协议(protocol)并添加以下代码:
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)
}
}
}
以及 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>
关于javascript - 在 Swift 中通过 UIWebView 从 Javascript 传递一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35824535/