当我将其快速加载到WKWebVIew时,我想从我的网页中删除页眉和页脚div标签。
我尝试了以下代码。但它没有用..
给我解决办法!
class ViewController: UIViewController {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
var url: URL?
url = URL(string: "https://www.walkmate.co.in")
let request = URLRequest(url: url!)
webView.load(request)
let script="function(){ var footer=document.getElementsByClassName('footer-env')[0]; footer.parentNode.removeChild(footer); })())"
webView.evaluateJavaScript(script) { (result, error) in
if error != nil {
print(result)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
我认为您应该等待网站加载。
您需要WKNavigationDelegate
并评估您的脚本
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)");
}
实际上,当您要评估脚本时,不会加载您的站点。
**更新**
你需要这样的东西
// add the protocol
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
var url: URL?
url = URL(string: "https://www.walkmate.co.in")
let request = URLRequest(url: url!)
webView.navigationDelegate = self // set the delegate
webView.load(request)
}
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)");
let script="function(){ var footer=document.getElementsByClassName('footer-env')[0]; footer.parentNode.removeChild(footer); })())"
webView.evaluateJavaScript(script) { (result, error) in
if error != nil {
print(result)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}