這將與WKWebView一起使用。不要忘了在上面的類定義添加的WebKit框架工作
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)
}
示例JavaScript代碼注入
//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);
您能提供一些關於您遇到的崩潰的信息嗎? – delannoyk 2014-10-28 13:50:02
「線程1:信號SIGABRT」 – user1731468 2014-10-28 13:55:06
您是使用'WKWebView'還是'UIWebView'? – mustafa 2014-10-30 14:23:20