I created a iOS web browser with swift language code. And add an extra button to inject a script on that web page, but it always crash when I try this:
webVi
This will work with WKWebView. Dont forget to add WebKit frame work on top on your class definition
var webView: WKWebView!
func loadWebViewWithCustomJavaScript {
//Create Preferences
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
//Initialise javascript file with user content controller and configuration
let configuration = WKWebViewConfiguration()
let scriptURL = NSBundle.mainBundle().pathForResource("Your File Name", ofType: "js")
var scriptContent = ""
do {
scriptContent = try String(contentsOfFile: scriptURL!, encoding: NSUTF8StringEncoding)
} catch{
print("Cannot Load File")
}
let script = WKUserScript(source: scriptContent, injectionTime: .AtDocumentStart, forMainFrameOnly: true)
configuration.userContentController.addUserScript(script)
configuration.preferences = preferences
//Create WebView instance
webView = WKWebView(frame: CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height), configuration: configuration)
view.addSubview(webView)
//Finally load the url
let url = NSURL(string:"your URL")
let urlRequest = NSURLRequest(URL: url!)
webView.loadRequest(urlRequest)
}
Sample JavaScript code for injection
//Hides name of "background1" element on the page
var styleTag = document.createElement("style");
styleTag.textContent = 'div#background1, .after-post.widget-area {display:none;}';
document.documentElement.appendChild(styleTag);