Inject a JavaScript code in Webview iOS

后端 未结 4 1815
闹比i
闹比i 2020-12-06 13:47

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:

webVi         


        
4条回答
  •  眼角桃花
    2020-12-06 14:22

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

提交回复
热议问题