Ehsan Ullah
Ehsan Ullah

Reputation: 185

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)!))

Upvotes: 4

Views: 1776

Answers (3)

Giang
Giang

Reputation: 2729

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)

Upvotes: 0

Imran Rasheed
Imran Rasheed

Reputation: 956

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
                        })
}

Upvotes: 3

Asad Farooq
Asad Farooq

Reputation: 205

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)
    })

}

Upvotes: 2

Related Questions