3

I am trying to exclude some webpage elements like sidebar by injecting a new CSS rule throughout javascript, I created a new javascript file in xcode with the a new style tag to hide the sidebar that I inspected in Google chrome developer tool and ended with this code:

var styleTag = document.createElement("style");
styleTag.textContent = '.sidebar {display:none;}';
document.documentElement.appendChild(styleTag);

and created WKWebViewConfiguration object which holds some properties that allow the creation of the bridge between native code and the hosted web content as described here but still not getting this script running.

This is my complete ViewController code:

import UIKit
import WebKit

class scrapedBrowser: UIViewController, WKNavigationDelegate {

var webView: WKWebView!
var progressView: UIProgressView!

override func loadView() {

    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}

required init?(coder aDecoder: NSCoder) {
    let config = WKWebViewConfiguration()
    let scriptURL = Bundle.main.path(forResource: "hideSections", ofType: "js")
    let scriptContent:String?
    do {
        scriptContent = try String(contentsOfFile: scriptURL!, encoding: String.Encoding.utf8)
    }
    catch _ {
        scriptContent = nil
    }

    let script = WKUserScript(source: scriptContent!, injectionTime: .atDocumentStart, forMainFrameOnly: true)
    config.userContentController.addUserScript(script)
    super.init(coder: aDecoder)
    self.webView?.navigationDelegate = self
}

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "http://yourwebsite.com/")!
    let request = URLRequest(url: url)
    webView.load(request)
    webView.allowsBackForwardNavigationGestures = true
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    title = webView.title
}

}
Abdullah Jafar
  • 104
  • 1
  • 9
  • 1
    There's a few references to JSContext that should help with what your after. https://developer.apple.com/reference/javascriptcore/jscontext And there's a swift 3 thread on [here](https://stackoverflow.com/a/40730365/4891259) – Warve Jan 25 '17 at 21:15
  • Thanks @JesseC , this is a good example of injecting CSS through JavaScript in iOS App, already implemented this one and got my App working as needed. – Abdullah Jafar May 21 '18 at 06:47

2 Answers2

0

You need to assign config to the WKWebView.

webView = WKWebView(frame: CGRect.zero, configuration: config)
BonzaiThePenguin
  • 1,413
  • 13
  • 19
0

You have created config and added script to in init and you haven't kept reference of config. Later on loadView you are creating wkwebview and not setting configuration you created earlier on in init

Atif
  • 286
  • 3
  • 14