swift2 通过Swift中的UIWebView从Javascript传递数组

8qgya5xd  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(172)

我不得不在我的项目中使用UIWebView,我似乎遇到了一个问题。
好吧,我有如下html.

  1. <html>
  2. <a onclick="myFunction(1)">element1</a>
  3. <a onclick="myFunction(2)">element1</a>
  4. <a onclick="myFunction(3)">element1</a>
  5. </html>

当我点击到a href链接时,我必须执行我的javascript代码

  1. <script>
  2. var arr = [];
  3. function myFunction(number) {
  4. arr.push(number);
  5. }
  6. </script>

现在,我如何将Array传递给UIViewController
以及如何在swift中知道是否从UIWebView调用myFunction()

vom3gejh

vom3gejh1#

您可以使用WKWebView(从OS X 10.10或iOS 8开始提供)来完成这项工作。在Xcode 9及更高版本中,您可以将WkWebView直接添加到Interface Builder并连接IBOutlet。对于较早版本的Xcode,您必须通过编程来完成此操作。为了实现完全兼容,以下代码显示了如何通过编程来添加WKWebView
使视图控制器符合WKScriptMessageHandler协议,并添加以下代码:

  1. class ViewController: UIViewController, WKScriptMessageHandler {
  2. weak var webView: WKWebView!
  3. override func viewDidLoad() {
  4. super.viewDidLoad()
  5. // myAction is the pipe name Javascript uses to post messages
  6. // to your app. You can define more than 1 pipe.
  7. let controller = WKUserContentController()
  8. controller.addScriptMessageHandler(self, name: "myAction")
  9. let config = WKWebViewConfiguration()
  10. config.userContentController = controller
  11. // Add the WKWebView to the view
  12. let frame = CGRectMake(20, 20, 200, 200)
  13. let webView = WKWebView(frame: frame, configuration: config)
  14. self.view.addSubview(webView)
  15. // Load your HTML file
  16. let url = NSBundle.mainBundle().URLForResource("mydoc", withExtension: "html")!
  17. webView.loadFileURL(url, allowingReadAccessToURL: url)
  18. // Pass reference to the view controller
  19. self.webView = webView
  20. }
  21. // Handle the message posted by Javascript
  22. func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
  23. if let arr = message.body as? [Int] {
  24. print(arr)
  25. }
  26. }
  27. }

以及HTML + Javascript:

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  4. <title>Hello world</title>
  5. <script type="text/javascript">
  6. var arr = [];
  7. function myFunction(number) {
  8. arr.push(number);
  9. // Send a message to your app on the myAction pipe
  10. window.webkit.messageHandlers.myAction.postMessage(arr);
  11. }
  12. </script>
  13. </head>
  14. <body>
  15. <a href="javascript:void(0)" onclick="myFunction(1)">element1</a>
  16. <a href="javascript:void(0)" onclick="myFunction(2)">element2</a>
  17. <a href="javascript:void(0)" onclick="myFunction(3)">element3</a>
  18. </body>
  19. </html>
展开查看全部

相关问题