> For the complete documentation index, see [llms.txt](https://jacky-chen.gitbook.io/jackychen/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jacky-chen.gitbook.io/jackychen/foundation/wkwebview-how-to-work-with-javascript.md).

# WKWebView how to work with javascript

## 教學連結

* [**js 向 Native 一句話傳值並反射出Swift 對象執行指定函數**](https://lvwenhan.com/ios/461.html)
* [**iOS下JS與OC互相調用（三）--MessageHandler**](https://www.jianshu.com/p/433e59c5a9eb1)
* [**代碼範例**](https://github.com/Haley-Wong/JS_OC/tree/master/JS_OC_MessageHandler)

## Memo

* **WKWebView 呼叫 javascript function**
  * 利用 - evaluateJavaScript:completionHandler:

    ```swift
    // 将分享结果返回给js
    NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
      NSLog(@"%@----%@",result, error);
    }];
    ```
* **javascript 向 WKWebView 傳值**

  * 蘋果在WKWebView 中的js runtime 裡事先註入了一個window\.webkit.messageHandlers.OOXX.postMessage() 方法，我們可以使用這個方法直接向Native 層傳值，異常方便。
  * 使用Safari 的WebAPP 開發工具，在當前頁面執行 js 傳值代碼

  ```swift
  // native App 將收到 name 為 OOXX，body 為 Hello WebKit!：
  window.webkit.messageHandlers.OOXX.postMessage("Hello WebKit!")
  ```

![](https://1934061725-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4XrCDvjc3xNfiB-3eT%2F-M4Y-TstkTXMD9Y8W9l7%2F-M4Y03bWRWQX-Fie_cnH%2Fsafari_console.png?alt=media\&token=cb3a2f6f-63f6-4e40-8b74-d1092e6bc9e9)
