我希望在将其加载到swift 4中的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.
}
}
答案 0 :(得分:1)
我认为你应该等待网站加载。
您需要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.
}
}