'How to hide header and footer in WKWebView using Js and ios-14

How to hide header and footer in WKWebView in swift in IOS 14 I am using below code for loadiing thr website inside webview.

 webview.load(URLRequest.init(url: URL.init(string: "myURLHere)!))


Solution 1:[1]

You need to use delegate function while loading the website like

self.webview.uiDelegate = self
webview.load(URLRequest.init(url: URL.init(string: 'url here')!))

and then inside the delegate method use following code.

   public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webview.evaluateJavaScript("document.getElementById(\"header_id\").style.display='none';document.getElementById(\"footer_id\").style.display='none';", completionHandler: { (res, error) -> Void in
        //Here you can check for results if needed (res) or whether the execution was successful (error)
    })

}

Solution 2:[2]

Try this code using CSS

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    let cssString = "header {display: none;}"
                   let script = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
                webView.evaluateJavaScript(script,
                        completionHandler: { (response, error) -> Void in
                    print(error)
                    webView.isHidden = false
                        })
                let cssString1 = "footer {display: none;}"
                   let script1 = "var style = document.createElement('style'); style.innerHTML = '\(cssString1)'; document.head.appendChild(style);"
                webView.evaluateJavaScript(script1,
                        completionHandler: { (response, error) -> Void in
                    webView.isHidden = false
                        })
}

Solution 3:[3]

We can use WKUserContentController to inject script to hide header, footer or something which you want

let contentController = WKUserContentController()
let script = "var style = document.createElement('style'); style.innerHTML = 'header {display: none;}'; document.head.appendChild(style);"
let scriptInjection = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
contentController.addUserScript(scriptInjection)
        
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
configuration.userContentController = contentController
let webview = WKWebView(frame: .zero, configuration: configuration)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asad Farooq
Solution 2 Imran Rasheed
Solution 3 Giang