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