最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

iphone - Inject a JavaScript code in Webview iOS - Stack Overflow

programmeradmin4浏览0评论

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:

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.

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./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.

Share Improve this question edited Oct 28, 2014 at 21:50 user1731468 asked Oct 26, 2014 at 13:31 user1731468user1731468 1,0002 gold badges10 silver badges32 bronze badges 4
  • Can you provide some information about the crash you have ? – delannoyk Commented Oct 28, 2014 at 13:50
  • "Thread 1:signal SIGABRT" – user1731468 Commented Oct 28, 2014 at 13:55
  • Are you using WKWebView or UIWebView ? – mustafa Commented Oct 30, 2014 at 14:23
  • I have converted that sample in github to WKWebView. I use WKWebView – user1731468 Commented Oct 30, 2014 at 14:42
Add a ment  | 

4 Answers 4

Reset to default 3

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.

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)
  }

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);

Got it working using following. Used String instead of NSString to use native swift 2. Javascript code to inject must be in 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!)

If you are using WKWebView here is a 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)

  1. 暂无评论