title: How to use CSS in WKWebView?
body: <p>I want to use a WKWebView to render a document. I made <code>Invoice.html</code> and <code>Invoice.css</code> and put them into bundle. When I load Invoice.html to Safari (by dragging file) everything looks OK. But not in WKWebView.
  I tried:</p>
  
  <p><strong>Simple way:</strong></p>
  
  <pre><code>let htmlUrl = URL(fileReferenceLiteralResourceName: "Invoice.html")
  let html = String.init(contentsOf: htmlUrl)
  webView.loadHTMLString(html, baseURL: nil)
  </code></pre>
  
  <p>Beginning of Invoice.html looks like this:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
      &lt;head&gt;
          &lt;meta charset="utf-8" /&gt;
          &lt;title&gt;Invoice&lt;/title&gt;
          &lt;link REL=StyleSheet HREF="./Invoice.css" TYPE="text/css" MEDIA=screen&gt;
              &lt;/head&gt;
      &lt;body id="Invoice" xml:lang="en-US"&gt;
          &lt;div class="page"&gt;
              &lt;div&gt;
                  &lt;p&gt;FAKTURA VAT&lt;/p&gt;
              &lt;/div&gt;
              &lt;div&gt;
                  &lt;div&gt;
                      &lt;p&gt;SPRZEDAWCA SELLER: &lt;/p&gt;
                  &lt;/div&gt;
                  &lt;p&gt;&lt;/p&gt;
  </code></pre>
  
  <p>I could see text in <code>WKWebView</code> but not styled.</p>
  
  <p><strong>WKWebView Extension</strong></p>
  
  <pre><code>extension WKWebView {
      func injectCSSFrom(url: URL) {
  
  
          let css = try! String(contentsOf: url).split(separator: "\n")
          //let css = "body { background-color : #aabbcc };"
          print (css)
          let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);"
  
          evaluateJavaScript(js) {(result, error) in
              if let error = error {
                  print("DOES NOT WORK", error)
              }
          }
      }
  }
  </code></pre>
  
  <p>prints :</p>
  
  <pre><code>body {
      margin: 0;
      padding: 0;
      background-color: #FA0000;
      font: 7pt "Helvetica";
  }
  
  .page {
      width: 21cm;
      height: 29.7cm;
      padding: 1.5cm;
      border: 1px #D3D3D3 solid;
      border-radius: 0px;
      background: white;
  }
  </code></pre>
  
  <p>Same like by simple way. Nothing, no style, no background color. But if I change <code>let css = "body { background-color : #aabbcc };"</code> at least background color changes.</p>
  
  <p>In both cases <code>evaluate...</code> throws an error <code>Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unexpected EOF, WKJavaScriptExceptionColumnNumber=0, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred}</code></p>
  
  <p>Is a simple and versatile way to attach <code>css</code> to <code>html</code> generated locally?</p>