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

半世苍凉 提交于 2019-11-29 15:55:14

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)

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!