Monti

Swift) webView-4 (웹의 Javascript 이벤트 실행) 본문

IOS/Swift

Swift) webView-4 (웹의 Javascript 이벤트 실행)

montt 2022. 10. 9. 23:28

Swift으로 웹의 Javascript 이벤트 실행

글자 입력 위한 HTML 수정

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type=""text/javascript>
        function outLink(link) {
            webkit.messageHandlers.outLink.postMessage(link)
        }

        function button() {
            webkit.messageHandlers.button.postMessage(true)
        }

                <!-- 버튼 클릭시 swift 함수 호출 -->
        function inputText() {
            webkit.messageHandlers.inputText.postMessage(true)
        }
    </script>    
    <title>WebView</title>
</head>

<body>
    <header>
        <button type="button" onclick="button()"> button </button>
    </header>

    <section>
        <button type="button" onclick="outLink('https://www.naver.com/')"> 네이버 이동 </button>
    </section>

    <section>
        <button type="button" onclick="outLink('https://www.apple.com/')"> 애플 이동 </button>
    </section>

        <!-- 
                swift에 이벤트를 줄 버튼
                swift에서 value값 받을 input 태그 생성
         -->
    <section>
        <button type="button" onclick="inputText()">텍스트 입력</button>
        <input type="text" id="inputText">
    </section>

</body>
</html>

Swift to Javascript

func setupWebView() {
        let contentController = WKUserContentController()

        // Bridge 등록
        contentController.add(self, name: "button")
        contentController.add(self, name: "outLink")

                // Bridge 추가 등록
                contentController.add(self, name: "inputText")

        // JavaScript Function 불러오기
        callJsFunc(contentController: contentController)

        let configuration = WKWebViewConfiguration()
        configuration.userContentController = contentController

        webView = WKWebView(frame: .zero, configuration: configuration)

    }

// 웹에서 document.getElementsById('inputText')[0].value = 'swift' 자바스크립트 실행
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    switch message.name {
    case "inputText":
        self.webView?.evaluateJavaScript("document.getElementById('inputText').value = 'swift'", completionHandler: nil)
    default:
        break
    }
}

전체 코드

import UIKit
import WebKit

class ViewController: UIViewController{
    private var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupWebView()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        loadWebView()
    }
}

private extension ViewController {

    func callJsFunc(contentController: WKUserContentController) {
        let userScript = WKUserScript(source: "button()", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        contentController.addUserScript(userScript)
    }

    func setupWebView() {
        let contentController = WKUserContentController()

        // Bridge 등록
        contentController.add(self, name: "button")
        contentController.add(self, name: "outLink")
        contentController.add(self, name: "inputText")

                // JavaScript Function 불러오기
        callJsFunc(contentController: contentController)

        let configuration = WKWebViewConfiguration()
        configuration.userContentController = contentController

        webView = WKWebView(frame: .zero, configuration: configuration)

    }
    func loadWebView() {
        guard let linkURL = URL(string: "https://kknd0806.github.io/simple_js_test/") else { navigationController?.popViewController(animated: true)
            return
        }
        view = webView
        let urlRequest = URLRequest(url: linkURL)
        webView.load(urlRequest)
    }
}

extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        switch message.name {
        case "button":
            let alert = UIAlertController(title: "Swift 버튼 함수", message:"버튼 클릭", preferredStyle: .alert)
            let action = UIAlertAction(title: "확인", style: .default, handler: nil)
            alert.addAction(action)
            self.present(alert, animated: true, completion: nil)
            break
        case "outLink":
            guard let outLink = message.body as? String,
                  let url = URL(string: outLink) else { return }

            let alert = UIAlertController(title: "OutLink 버튼 클릭", message: "URL : \(outLink)", preferredStyle: .alert)
            let action = UIAlertAction(title: "링크 열기", style: .default) { _ in
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
            let cancelAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)
            alert.addAction(action)
            alert.addAction(cancelAction)
            self.present(alert, animated: true, completion: nil)
            break
        case "inputText":
            self.webView?.evaluateJavaScript("document.getElementById('inputText').value = 'swift'", completionHandler: nil)
        default:
            break
        }
    }
}

테스트 결과

텍스트 입력 버튼 클릭 전
텍스트 입력 버튼 클릭 후

Comments