问题描述
我创建了一个带有快速语言代码的iOS网络浏览器。并添加一个额外的按钮来在该网页上注入脚本,但是当我尝试这个时它总是崩溃:
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:
webView!.evaluateJavaScript("document.body.style.background = 'red';", nil)
任何想法怎么解决这个问题?以及如何从文件中读取JavaScript代码,然后将其注入到该webview元素。
Any idea how to fix this? And how to read the JavaScript code from a file, and then inject it to that webview element.
我使用代码样式作为此示例,但使用 WKWebView :
I use the code style as this example but with WKWebView: https://github.com/rshankras/WebViewDemo
如果你能解决这个问题,我需要一个基本的工作代码。以及如何从文件加载JavaScript的解决方案。并将该代码注入WKWebView元素。
推荐答案
这将适用于WKWebView。别忘了在类定义的顶部添加WebKit框架工作
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)
}
示例JavaScript注入代码
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);
这篇关于在Webview iOS中注入JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!