0%

swift和网页的简单交互

前言

本文仅限于 UIWebView/WKWebview 和 swift 的交互,如果需要 js 直接交互请查看 JSPatch 。

UIWebView

  1. webView 传递给 swift
    利用 request.URL.scheme。例如约定一个 com.myapp。则发请求时

    url=com.myapp://?function=functionName&params=params
    
  2. swift 接收
    先解析 url,然后在代理方法 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool 中,

    if request.URL.scheme == com.myapp {
      self.functionName(params)
    }
    
  3. swift 传递给 webView

    webView.stringByEvaluatingJavaScriptFromString(jsString)

WKWebView

  1. 方法一

    1. 初始化,遵循 WKNavigationDelegate, WKUIDelegate

      1
      2
      web = WKWebView.init(frame: CGRect(x: 0, y: 0, width: 300, height: 500), configuration: WKWebViewConfiguration())
      web.navigationDelegate = self

    2. 拦截URL

      1
      2
      3
      4
      5
      6
      7
      func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
      print(navigationAction.request.url)
      //在这里执行操作
      self.evaluateJavaScript(js)
      decisionHandler(.cancel)
      return
      }

  2. 方法二

    1. swift

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      class MyWebView: WKWebView, WKScriptMessageHandler {

      class func webView(frame: CGRect) -> MyWebView {
      let contentController = WKUserContentController()

      let config = WKWebViewConfiguration()
      config.userContentController = contentController

      let webView = MyWebView.init(frame: frame, configuration: config)
      contentController.add(webView, name: "test")

      return webView
      }

      func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
      print(message.name)
      print(message.body)
      }
      }
      1
      2
      3
      @IBAction func buttonTap(_ sender: Any) {
      webView.evaluateJavaScript("changeColor('blue')", completionHandler: nil)
      }
    2. html

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      <!DOCTYPE HTML>
      <html lang="zh-cn">
      <head>
      <meta charset="utf-8" />
      <script type="text/javascript">
      function test() {
      // alert("test");
      window.webkit.messageHandlers.test.postMessage("test message");
      }

      function changeColor(color) {
      var h1 = document.getElementsByTagName('h1')
      h1[0].style.color = color;
      }

      </script>
      </head>
      <body>

      <h1>我的第一个标题</h1>

      <p>我的第一个段落。</p>
      <button onclick="test()">Test!</button>

      </body>
      </html>