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

﹥>﹥吖頭↗ 提交于 2020-01-10 05:27:06

问题


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.


回答1:


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)



回答2:


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 


来源:https://stackoverflow.com/questions/28434268/injecting-a-new-stylesheet-into-a-website-via-uiwebview-using-ios8-swift-xcode-6

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