Skip to content

Instantly share code, notes, and snippets.

@devxoul
Created July 3, 2018 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devxoul/ea4864d94d9822fa2e5a80e67321cc17 to your computer and use it in GitHub Desktop.
Save devxoul/ea4864d94d9822fa2e5a80e67321cc17 to your computer and use it in GitHub Desktop.
Set UIWebView's background color to document body's background color
self.webView.rx.didFinishLoad
.subscribe(onNext: { [weak self] in
guard let `self` = self else { return }
let script = "window.getComputedStyle(document.body).backgroundColor;"
guard let result = self.webView.stringByEvaluatingJavaScript(from: script) else { return }
let optionalComponents = result
.components(separatedBy: "(").safe[1]?
.components(separatedBy: ")").safe[0]?
.components(separatedBy: ",")
.map { $0.trimmingCharacters(in: .whitespaces) }
.compactMap { Float($0) }
.compactMap { CGFloat($0) }
guard let components = optionalComponents, components.count >= 3 else { return }
let red = components[0] / 255
let green = components[1] / 255
let blue = components[2] / 255
let alpha = components.safe[3] ?? 1
self.view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
})
.disposed(by: self.disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment