5

If someone has experience with WKWebView, please share how to make the background of the view transparent. The WebView object has such option via var drawsBackground: Bool { get set } but it is missing for the WKWebView class. I searched the net and .. found nothing. Before time it was possible to do so via opaque property, but not anymore. There is a getter isOpaque ... and that's it. I don't want to do it via CSS and already tried everything else, like:

webview.wantsLayer = true

webview.layer?.backgroundColor = NSColor.clear.cgColor

If someone can help ...

I. Nikolov

Community
  • 1
  • 1
Ivaylo Nikolov
  • 501
  • 4
  • 13
  • Possible duplicate of [Transparent background WKWebView (NSView)](http://stackoverflow.com/questions/27211561/transparent-background-wkwebview-nsview) – l'L'l Oct 12 '16 at 20:53
  • Not a duplicate. I've tried everything written in there - it's not working anymore. And I have described this in the question. – Ivaylo Nikolov Oct 12 '16 at 20:57
  • Please don't include the answer in your question. If an answer solved your issue, mark the answer as accepted; you can also post your own answer if you think it can be helpful to other users. Thank you. – Eric Aya Nov 24 '16 at 11:33

2 Answers2

12

This should work for both macOS 10.11 and macOS 10.12:

if NSAppKitVersion.current.rawValue > 1500 {
    webView.setValue(false, forKey: "drawsBackground")
}
else {
    webView.setValue(true, forKey: "drawsTransparentBackground")
}

Remark: this has been passed by App Store review.

Ely
  • 8,259
  • 1
  • 54
  • 67
  • Let me try it. Would it pass the review? Any experience with this? – Ivaylo Nikolov Oct 26 '16 at 18:36
  • OK. It is working. I'm not sure that this will pass the review, but I'll give it a try and will mark your answer as correct. Thank you for the help ;-) – Ivaylo Nikolov Oct 26 '16 at 18:40
  • I have submitted a Feedback Assistant report about this: https://github.com/feedback-assistant/reports/issues/81 If you also want to see this being officially supported, please duplicate this report. – Sindre Sorhus Jan 17 '20 at 07:08
  • As of ~iOS14 `drawsTransparentBackground` is deprecated and should not be used anymore (although there is no real alternative) – Lerk Jan 03 '21 at 04:04
0

Your web page should have transparent background as well.

Heisenbug
  • 951
  • 6
  • 25
  • If I call `webview.setValue(true, forKey: "drawsTransparentBackground")` it becomes transparent, but in the console there is a message : `[WKWebView _setDrawsTransparentBackground:] is deprecated and should not be used.`. The problem is not in the web page not being transparent. – Ivaylo Nikolov Oct 12 '16 at 21:16
  • @IvayloNikolov: this was the correct method in macOS 10.11. The deprecation in macOS 10.12 should be the real issue as part of your question. – Ely Oct 26 '16 at 16:06
  • Yes - exactly. You are correct. Still can't find the answer. – Ivaylo Nikolov Oct 26 '16 at 18:34