Skip to content

Instantly share code, notes, and snippets.

@daniloc
Created January 23, 2020 15:30
Show Gist options
  • Save daniloc/441cb1ba850dba275ff3e361229ef408 to your computer and use it in GitHub Desktop.
Save daniloc/441cb1ba850dba275ff3e361229ef408 to your computer and use it in GitHub Desktop.
Provide your own CSS to a WKWebView instance, even if it's loaded from a nib or storyboard.
extension WKWebView {
//via https://stackoverflow.com/a/53706678
//and https://stackoverflow.com/a/53141055
func applyStylesheet() {
guard
let path = Bundle.main.path(forResource: "style", ofType: "css"), //load style.css from your app bundle
let cssString = try? String(contentsOfFile: path).components(separatedBy: .newlines).joined()
else {
return
}
let source = """
var style = document.createElement('style');
style.innerHTML = '\(cssString)';
document.head.appendChild(style);
"""
let userScript = WKUserScript(source: source,
injectionTime: .atDocumentEnd,
forMainFrameOnly: true)
self.configuration.userContentController.addUserScript(userScript)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment