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.
Use injectJavaScript as per (Guide > Communicating between JS and Native > The injectJavaScript method)[https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#the-injectjavascript-method"]. In your case, that would be something like this. webview. injectJavaScript(jsCode)
WebView can be defined as an object which can display the interactive web content and load HTML strings within the iOS application for an in-app browser. It is an instance of the WKWebView class, which inherits the UIView class.
A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With