Created
January 23, 2020 15:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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