Search code examples
iosswiftuiwebviewwkwebview

Swift: Injecting JS & CSS to WKWebView doesn't work


I'd like to try injecting js script to the WKWebView but it doesn't work. So it is a web but when it's loaded on the App, we should hide the header and footer. I fetch the CSS URL from the config and load it and try to inject it along with the JS written on the code. But, the web is loaded but the expected things doesn't work. What's wrong?

This is the code (I omit many of unrelated code to the question)

import UIKit
import WebKit

class CustomPageWebViewController: UIViewController, WKNavigationDelegate {

    private var webView: WKWebView = WKWebView()


    override func viewDidLoad() {
        super.viewDidLoad()

        webView.navigationDelegate = self
        view.addSubview(webView)

        // Request web page
        requestWebPage()

    }


    // MARK: - Request Web Page

    func requestWebPage() {
        if let urlString = URL(string: determineURLBasedOnPaymentName()) {
            webView.load(URLRequest(url: urlString))
        }
    }


    //

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        removeHeaderAndFooter(webView: webView)
    }

    func removeHeaderAndFooter(webView: WKWebView) {
        let cssURLString = ConfigManager.sharedInstance.cssURL
        if cssURLString != "" {
            let cssURL = URL(string: cssURLString)
            if let cssURL = cssURL {
                let sessionConfig = URLSessionConfiguration.default
                let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
                var request = URLRequest(url: cssURL)
                request.httpMethod = "GET"

                let task = session.dataTask(with: request, completionHandler: { (data: Data!, response: URLResponse!, error: Error!) -> Void in
                    if (error == nil) {
                        let result = String(data: data, encoding: String.Encoding.utf8)!

                        var js = "!function(){var e=document.createElement(\"style\");e.type=\"text/css\",e.innerHTML=window.atob(%@),document.getElementsByTagName(\"head\")[0].appendChild(e);var t=document.createElement(\"style\");t.type=\"text/css\",t.innerHTML=\"#tab-hotel,#tabs-2,.rail-order__flex{display:none;} .search__label--input{height:45px;} #tabs-2{display:block;}\",document.body.appendChild(t)}();"
                        // So after I get the CSS file from the link, I will inject it to the JS file here
                        js = String(format: js, result)

                        // And then inject the whole script to the webview
                        self.webView.evaluateJavaScript(js, completionHandler: { (any, error) in

                        })
                    }
                })
                task.resume()
            }
        }
    }
}

Solution

  • Please use UIWebView and webView.stringByEvaluatingJavaScript(from: "")