Skip to content

Instantly share code, notes, and snippets.

@daniloc
Created January 23, 2020 15:30
Show Gist options
  • Save daniloc/441cb1ba850dba275ff3e361229ef408 to your computer and use it in GitHub Desktop.
Save daniloc/441cb1ba850dba275ff3e361229ef408 to your computer and use it in GitHub Desktop.

Revisions

  1. daniloc revised this gist Jan 23, 2020. No changes.
  2. daniloc revised this gist Jan 23, 2020. No changes.
  3. daniloc revised this gist Jan 23, 2020. No changes.
  4. daniloc created this gist Jan 23, 2020.
    26 changes: 26 additions & 0 deletions WebViewCSSExtension.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    extension WKWebView {

    //via https://stackoverflow.com/a/53706678
    //and https://stackoverflow.com/a/53141055

    func applyStylesheet() {
    guard
    let path = Bundle.main.path(forResource: "style", ofType: "css"), //load style.css from your app bundle
    let cssString = try? String(contentsOfFile: path).components(separatedBy: .newlines).joined()
    else {
    return
    }

    let source = """
    var style = document.createElement('style');
    style.innerHTML = '\(cssString)';
    document.head.appendChild(style);
    """

    let userScript = WKUserScript(source: source,
    injectionTime: .atDocumentEnd,
    forMainFrameOnly: true)

    self.configuration.userContentController.addUserScript(userScript)
    }
    }