Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

iphone - Inject a JavaScript code in Webview 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)

Any idea how to fix this? And how to read the JavaScript code from a file, and then inject it to that webview element.

I use the code style as this example but with WKWebView: https://github.com/rshankras/WebViewDemo

If you can solve this question I need a basic working code in the answer. And solution for how to load the JavaScript from a file. And inject that code in the WKWebView element.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't see the method you are using (evaluateJavaScript) in the current UIWebView API docs but it is in the WKWebView docs. Maybe you are using the wrong API? Perhaps try using stringByEvaluatingJavaScriptFromString(_:) instead:

let script = "document.body.style.background = 'red'"
if let result = webView.stringByEvaluatingJavaScriptFromString(script) {
    println("result is (result)")
}

Also, i'm not sure if the "!" is needed (a hunch tells me it's not), as there is no context around your code. So maybe try both versions.

Getting a string from a file is something like:

let path = NSBundle.mainBundle().pathForResource("jsFileName", ofType: "js")
if let content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil) {
    println("js content is (content)")
}

Loading from disk has a lot of variables around how your file is being copied and stored so your going to have to do some work to fit the path variable to your structure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...