how to hide html elements in wkwebview in IOS?

偶尔善良 提交于 2021-02-19 08:11:51

问题


i want to hide certain html elements in wkwebview using swift 4, xcode 9. i know how to do it in android and have added the code below. i just need an equivalent code for ios in swift 4 for wkwebView.

myWebView.setWebViewClient(new WebViewClient()
        {  
            @Override  
            public void onPageFinished(WebView view, String url)  
            {  
                myWebView.loadUrl("javascript:(function() { " +  
                        "document.getElementById('divHeader') 
[0].style.display='none'; " +  
                        "})()");  
            }  
        });  

        myWebView.loadUrl(URL);

回答1:


Use WKWebView

import WebKit

class FirstViewController: UIViewController, WKNavigationDelegate {

@IBOutlet weak var webVw: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    webVw.navigationDelegate = self
    loadmyPage(htmlstr: "https://www.mywebsite.com")
}

func loadmyPage(htmlstr:String){
    let url = URL (string: htmlstr)
    let request = URLRequest(url: url!)
    webVw.load(request)
}

//MARK:- WKNavigationDelegate
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    print(error.localizedDescription)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Start to load")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("finish to load")
    let elementID = "right_sidebar"
    let removeElementIdScript = "var element = document.getElementById('\(elementID)'); element.parentElement.removeChild(element);"
    webView.evaluateJavaScript(removeElementIdScript) { (response, error) in
        debugPrint("Am here")
    }
}


来源:https://stackoverflow.com/questions/50822699/how-to-hide-html-elements-in-wkwebview-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!