Embed JavaScript code in Webview iOS

I created an iOS web browser with a fast language code. And add an extra button to enter the script on this web page, but it always crashes when you try:

webView!.evaluateJavaScript("document.body.style.background = 'red';", nil) 

Any idea how to fix this? And how to read JavaScript code from a file, and then enter it into this web viewer.

I use a code style like this example, but with WKWebView: https://github.com/rshankras/WebViewDemo

If you can solve this question, I need the basic working code in the answer. And a solution for loading JavaScript from a file. And add this code to the WKWebView element.

+5
source share
4 answers

I do not see the method that you use (evaluate JavaScript) in the current UIWebView API Documents , but it is in the WKWebView Documents . Maybe you are using the wrong API? Maybe 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 that "!" (prediction tells me this is wrong), since there is no context around your code. So maybe try both versions.

Getting a line from a file looks something like this:

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

Booting from disk has many variables around how your file is copied and stored, so you will have to do some work to match the path variable in your structure.

+2
source

This will work with WKWebView. Remember to add the WebKit framework on top of 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 Injection Code

  //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); 
+2
source

Got a job using the following. Used String instead of NSString to use native swift 2. Javascript code for injection should be in the hidesections.js file

  let jsPath = NSBundle.mainBundle().pathForResource("hidesections", ofType: "js"); let jsContent: String? do { jsContent = try String(contentsOfFile: jsPath!, encoding: NSUTF8StringEncoding) } catch _ { jsContent = nil } webView.stringByEvaluatingJavaScriptFromString(jsContent!) 
+1
source

If you are using WKWebView , here is the solution.

 if let scriptFile = NSBundle.mainBundle().pathForResource("script", ofType: "js") { var error: NSError? let scriptString = NSString(contentsOfFile: scriptFile, encoding: NSUTF8StringEncoding, error: &error) if let error = error { println("Error: Could not load script file => \(error)") } else { if let scriptString = scriptString { let script = WKUserScript(source: scriptString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true) let controller = WKUserContentController() controller.addUserScript(script) let configuration = WKWebViewConfiguration() configuration.userContentController = controller let webView = WKWebView(frame: self.view.bounds, configuration: configuration) self.webView = webView self.view.addSubview(webView) } } } 
0
source

Source: https://habr.com/ru/post/1205542/


All Articles