Injecting a new stylesheet into a website via uiwe

2020-02-14 10:27发布

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 of example, let's say its google.com.

@IBOutlet var website: UIWebView!

var url = "http://www.google.com"

func loadUrl() {
    let requestURL = NSURL(string: url)
    let request = NSURLRequest(URL: requestURL!)
    website.loadRequest(request)
}

override func viewDidLoad() {
    super.viewDidLoad()
    website.delegate = self
    loadUrl()
}

func webViewDidFinishLoad(website: UIWebView) {
    var jsscript = "some script here"
    website.stringByEvaluatingJavaScriptFromString(jsscript)
}

Using Swift, how would I inject a whole new stylesheet into the website so I can overwrite many of the styles?

Also, I'd like the new stylesheet to exist in one of my app's directories. Where is the best directory for that to be? Under "Supporting files?" And, how would I call that path in my code?

It would also be nice if the website wouldn't load until the styles had been applied.

2条回答
三岁会撩人
2楼-- · 2020-02-14 11:14

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 
查看更多
爷、活的狠高调
3楼-- · 2020-02-14 11:21

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)
查看更多
登录 后发表回答