Inject a JavaScript code in Webview iOS

后端 未结 4 1813
闹比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:23

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

提交回复
热议问题