Enable Inspector in WKWebView under SwiftUI & SplitView

I am running this on MacOS, Xcode version 11.6.

In order to run this code you must add com.apple.security.network.client with the value true to your entitlements file.

I want to enable the Inspector for WKWebView. I have created an NSViewRepresentable to encapsulate the WKWebView. Here is the simplified code:

Code Block swift
struct WKWebViewRepresentable: NSViewRepresentable {
var urlToDisplay: URL?
var enableDeveloperTools: Bool = false
func loadData(wkWebView: WKWebView) {
if let url = urlToDisplay {
wkWebView.load(URLRequest(url: url))
}
}
func makeNSView(context: Context) -> WKWebView {
let wkWebView = WKWebView()
wkWebView.configuration.preferences.setValue(enableDeveloperTools, forKey: "developerExtrasEnabled")
loadData(wkWebView: wkWebView)
return wkWebView
}
func updateNSView(_ wkWebView: WKWebView, context: Context) {
loadData(wkWebView: wkWebView)
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
}
extension WKWebViewRepresentable {
class Coordinator: NSObject {
init(_ parent: WKWebViewRepresentable) {
super.init()
}
}
}


and with this code in place I can create the following ContentView:

Code Block swift
struct ContentView: View {
static let demoURL = "https://" + "www.apple.com/apple-music/"
var body: some View {
HStack {
WKWebViewRepresentable(urlToDisplay: URL(string: ContentView.demoURL), enableDeveloperTools: true)
WKWebViewRepresentable(urlToDisplay: URL(string: ContentView.demoURL), enableDeveloperTools: false)
}
}
}


The good news is that the above code actually works. If you right click on the left hand side, you can select Inspect Element which will start the Inspector.

The idea is that I would do discovery on the left hand side and do show the processed result on the right hand side. That part is obviously not in the code. For testing purposes the right hand side simply shows the same content as the left hand side.

I would like to see that the user is being able to split the real-estate between the two views, hence I replace
the HStack with HSplitView, no other change. When you run this code, the WkWebView's come up as before but one you select Inspect Element the place where the Inspector should show is blank (black or white depending on dark mode), it starts flashing etc. By dragging inside that rectangle, it becomes clear that the code is actually running just not properly rendering.

This stackoverflow article, mentions the same problem and it suggests that autolayout should be disabled.

Does anyone know a trick to circumvent this layout problem for SwiftUI?

Hey @FredA, were you able to solve this in SwiftUI?

Enable Inspector in WKWebView under SwiftUI & SplitView
 
 
Q