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

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

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

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

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

<script>
var arr = [];
function myFunction(number) {
    arr.push(number);
}
</script>

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

vom3gejh

vom3gejh1#

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

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>

相关问题