我正在尝试使用WKWebView
将javascript代码实现到我的swift应用程序中,将js
用于快捷方式并使用safari工作运行它。
如何实现这个脚本以适应我的webview
?
override func viewDidLoad() {
super.viewDidLoad()
//self.navigationItem.hidesBackButton = false
self.navigationItem.setHidesBackButton(false, animated:true)
let script = """
LONG SCRIPT HERE
"""
let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: true)
let contentController = WKUserContentController()
contentController.addUserScript(userScript)
let webViewConfiguration = WKWebViewConfiguration()
webViewConfiguration.userContentController = contentController
let viewContainer = WKWebView(frame: CGRect(x:0, y:0, width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height), configuration: webViewConfiguration)
let startURL = URL(string: "MY URL")
let myURLRequest:URLRequest = URLRequest(url: startURL!)
viewContainer.load(myURLRequest)
self.view.addSubview(viewContainer)
viewContainer.navigationDelegate = self
}
您可以在evaluateJavaScript()
中使用所谓的WkWebView
,然后在Swift代码中读取结果。
这是一个简单的例子:
webView.evaluateJavaScript("document.getElementById('someElement').innerText") { (result, error) in
if error != nil {
print(result)
}
}