Injecting a new stylesheet into a website via uiwebview using iOS8 Swift XCode 6

后端 未结 2 620
难免孤独
难免孤独 2020-12-21 14:57

I\'ve seen a few options on here using just Objective-C, but I\'m having trouble doing this with Swift iOS8 in XCode 6. I\'m using the uiwebview to load a website. For sake

相关标签:
2条回答
  • 2020-12-21 15:25

    So, I think I found at least one way to accomplish appending styles to the webpage being loaded using Swift:

      var loadStyles = "var script = 
      document.createElement('link');
      script.type = 'text/css';
      script.rel = 'stylesheet';
      script.href = 'http://fake-url/styles.css';
      document.getElementsByTagName('body')[0].appendChild(script);"
    
      website.stringByEvaluatingJavaScriptFromString(loadStyles)
    
    0 讨论(0)
  • 2020-12-21 15:27

    Using the now preferred WKWebView you can put the external css file, say tweaks.css in the root of your project or in a sub-folder, then you can inject it into your page like this:

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        guard let path = Bundle.main.path(forResource: "tweaks", ofType: "css") else { return }
        let css = try! String(contentsOfFile: path).replacingOccurrences(of: "\\n", with: "", options: .regularExpression)
        let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);"
        webView.evaluateJavaScript(js)
    }
    

    To make the file available:

    1. Click your project
    2. Click your target
    3. Select Build Phases
    4. Expand Copy Bundle Resources
    5. Click '+' and select your file.

    Also make sure that your controller implements WKNavigationDelegate:

    class ViewController: UIViewController, WKNavigationDelegate 
    
    0 讨论(0)
提交回复
热议问题