我在网址中加载了UIWebKit
,并且我希望在单击时选择html元素的ID。我可以在知道ID的情况下获取元素,但是单击该元素时如何获取未知的元素ID。
感谢你们对我的帮助 !
答案 0 :(得分:0)
您可以按照以下方式进行操作。
WKUserScript
将一些javascript注入WebView。elementFromPoint
查找DOM元素。我已经测试了这种工作方式,并且对我有用。
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
private var url = URL(string: "https://www.google.com")!
override func viewDidLoad() {
super.viewDidLoad()
initializeWebView()
loadData()
}
private func initializeWebView() {
let javascript = """
window.onload = function() {
document.addEventListener("click", function(evt) {
var tagClicked = document.elementFromPoint(evt.clientX, evt.clientY);
window.webkit.messageHandlers.jsMessenger.postMessage(tagClicked.outerHTML.toString());
});
}
"""
let userScript = WKUserScript.init(source: javascript,
injectionTime: .atDocumentStart, forMainFrameOnly: true)
webView.configuration.userContentController.addUserScript(userScript)
webView.configuration.userContentController.add(self, name: "jsMessenger")
}
private func loadData() {
let request = URLRequest(url: url)
webView?.load(URLRequest.init(url: url))
}
}
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.body)
}
}
它为您提供整个元素作为字符串
答案 1 :(得分:0)
ViewController类:UIViewController,WKNavigationDelegate,WKUIDelegate {
@IBOutlet weak var webContentView: UIView!
var web: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
let JSsource = """
window.onload = function() {
document.addEventListener("click", function(evt) {
var tagClicked = document.elementFromPoint(evt.clientX, evt.clientY);
window.webkit.messageHandlers.jsMessenger.postMessage(tagClicked.outerHTML.toString());
});
}
"""
let script = WKUserScript(source: JSsource, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
config.userContentController.addUserScript(script)
config.userContentController.add(self as! WKScriptMessageHandler, name: "jsMessenger")
self.web = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height-60), configuration : config)
self.web.navigationDelegate = self
self.web.uiDelegate = self
self.webContentView.addSubview(self.web!)
}
func userContentController(_ userContentController:WKUserContentController,didReceive消息:WKScriptMessage){ 打印(message.body) }