问题
I am building a Mac application using Swift. Therefor, I want to make a WKWebView transparent, so it shows the text of the loaded HTML, but the background of my underlaying NSWindow is visible. I tried
webView.layer?.backgroundColor = NSColor.clearColor().CGColor;
which hadn't any effect. WKWebView inherits from NSView, but I don't know if this helps.
Another solution would be to insert a NSVisualEffectView as the background of the WebView, but I don't know how to accomplish that, either!
回答1:
It was not supported, then they fixed it:
https://bugs.webkit.org/show_bug.cgi?id=134779
The way to make it transparent is to:
myWebView.opaque = false
回答2:
Code below works for me perfectly, also color is set to clearColor by default.
[wkWebView setValue:YES forKey:@"drawsTransparentBackground"];
回答3:
Use this in macOS 10.12 and higher:
webView.setValue(false, forKey: "drawsBackground")
回答4:
I used this for macOS 10.12. without problems in OjbC:
[self.webView setValue:@YES forKey:@"drawsTransparentBackground"];
Under macOS 10.13.+ I got the following console warning message:
-[WKWebView _setDrawsTransparentBackground:] is deprecated and should not be used
The ONLY working solution was:
[self.webView setValue:@(NO) forKey:@"drawsBackground"];
I tried the below in many scenarios and it didn't work:
- give the webView and the enclosingScrollView a layer and edit it's properties (backgroundColor, isOpaque)
- give the webView and the enclosingScrollView a clear background color
- inject javascript without the setValue forKey: in the webview.
Additionally I did use:
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
if (self.isWebviewsBackgroundTransparent) {
[self insertTransparentBackgroundTo:webView];
}
}
- (void)insertTransparentBackgroundTo:(WKWebView *)webView
{
NSString *transparentBackgroundJSSString = @"document.body.style = document.body.style.cssText + \";background: transparent !important;\";";
[webView evaluateJavaScript:transparentBackgroundJSSString completionHandler:nil];
}
来源:https://stackoverflow.com/questions/27211561/transparent-background-wkwebview-nsview