[swift ios] Inject JavaScript into WKWebView : webview에 javascript 삽입

Inject JavaScript into WKWebView

In Swift, it is possible to inject a JavaScript code into a WKWebView and execute it from your app. The below code example demonstrates how to:

  • Load HTML file from a local file,
  • Load JavaScript code from a local file,
  • Create WKUserScript object,
  • Inject JavaScript into an HTML document.

Load HTML File From App Bundle

let myProjectBundle:Bundle = Bundle.main
let myUrl = myProjectBundle.url(forResource: "my-html-file", withExtension: "html")!
myWebView.loadFileURL(myUrl,allowingReadAccessTo: myUrl)

Load JavaScript Code From a Local File

The below code example is a function which you can add to your Swift file and call to load the content of a demo-script.js file.

func getMyJavaScript() -> String {
if let filepath = Bundle.main.path(forResource: "demo-script", ofType: "js") {
do {
return try String(contentsOfFile: filepath)
} catch {
return ""
}
} else {
return ""
}
}

where:

demo-script – is the name of a file. Notice that there is no need to specify file extension here.
js – The demo-script file extension.

Inject JavaScript to WKWebView with WKUserScript

var myWebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
 
let config = WKWebViewConfiguration()
let js = getMyJavaScript()
let script = WKUserScript(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
 
config.userContentController.addUserScript(script)
config.userContentController.add(self, name: "clickListener")
 
myWebView = WKWebView(frame: view.bounds, configuration: config)
myWebView.uiDelegate = self
myWebView.navigationDelegate = self
view.addSubview(myWebView!)
}

where:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

getMyJavaScript() – is a function that loads JavaScript from a local file. The source code of this function is also on this page.

Complete Example

import UIKit
import WebKit
 
class MyWebViewViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
 
 
 
var myWebView: WKWebView!
 
override func viewDidLoad() {
super.viewDidLoad()
 
let config = WKWebViewConfiguration()
let js = getMyJavaScript()
let script = WKUserScript(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
 
config.userContentController.addUserScript(script)
config.userContentController.add(self, name: "clickListener")
 
myWebView = WKWebView(frame: view.bounds, configuration: config)
myWebView.uiDelegate = self
myWebView.navigationDelegate = self
view.addSubview(myWebView!)
 
}
 
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
 
let myProjectBundle:Bundle = Bundle.main
 
let myUrl = myProjectBundle.url(forResource: "my-html-file", withExtension: "html")!
myWebView.loadFileURL(myUrl,allowingReadAccessTo: myUrl)
 
//let url = URL(string: "https://appsdeveloperblog.com")!
//myWebView.load(URLRequest(url: url))
 
}
func getMyJavaScript() -> String {
if let filepath = Bundle.main.path(forResource: "demo-script", ofType: "js") {
do {
return try String(contentsOfFile: filepath)
} catch {
return ""
}
} else {
return ""
}
}
 
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
 
}
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

[출처] https://www.appsdeveloperblog.com/inject-javascript-into-wkwebview/

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수

등록된 글이 없습니다.

대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED