Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
27 | 28 | 29 | 30 |
Tags
- MVVM
- UITabBarController
- WebView
- webview javascript
- ios
- JavaScript
- Vue.js
- vuejs
- 스위프트기초
- 비동기프로그래밍
- WKWebView
- Vue
- Node
- swiftarchitecture
- rxswift
- SWIFT
- Java
- Spring
- programmers12969
- URLSession
- 스위프트
- node.js
- UIKit
- 12969
- STS
- STS3
- 스위프트아키텍처
- HTTP
- webviewControll
- NotificationCenter정의
Archives
- Today
- Total
Monti
Swift) webView-4 (웹의 Javascript 이벤트 실행) 본문
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
}
}
}
테스트 결과
'IOS > Swift' 카테고리의 다른 글
Swift ) WkWebView - Cookie (0) | 2022.10.17 |
---|---|
Swift) Webview-5 웹뷰 컨트롤 (0) | 2022.10.09 |
Swift) webView-3 (JavaScript 클릭 이벤트 발생시키기) (0) | 2022.10.09 |
swift) webview-2 (자바스크립트 버튼 클릭 이벤트 핸들링) (0) | 2022.10.08 |
swift) webview-1 (0) | 2022.10.08 |
Comments