如何在WKWebView中使用URL加载CSS文件

问题描述 投票:0回答:2

我想通过使用URL链接注入CSS

正在工作

下面的代码,如果我将CSS文件存储在项目的Bundle路径中,

    lazy var webView: WKWebView = {
    guard let path = Bundle.main.path(forResource: "style", ofType: "css") else {
        return WKWebView()
    }

    let cssString = try! String(contentsOfFile: path).components(separatedBy: .newlines).joined()
    let source = """
    var style = document.createElement('style');
    style.innerHTML = '\(cssString)';
    document.head.appendChild(style);
    """
    let preferences = WKPreferences()
    preferences.setValue(true, forKey:"developerExtrasEnabled")
    let userScript = WKUserScript(source: source,
                                  injectionTime: .atDocumentEnd,
                                  forMainFrameOnly: true)

    let userContentController = WKUserContentController()
    userContentController.addUserScript(userScript)

    let configuration = WKWebViewConfiguration()
    configuration.userContentController = userContentController
    configuration.preferences = preferences

    let webView = WKWebView(frame: .zero,
                            configuration: configuration)
    webView.navigationDelegate = self
    webView.scrollView.isScrollEnabled = false
    webView.scrollView.bounces = false
    return webView
}()

期望

我有存储在我们服务器中的CSS文件,具有一些路径链接,说吧,

https://xyz/styles/style.css

所以我想通过使用URL链接来应用style.css文件,

[请帮助我仅通过使用URL来应用CSS文件,我不想将其存储在bundle中,bundle CSS文件已经对我有用,我们的CSS样式将动态变化,因此我想应用URL链接CSS文件。] >

我想通过使用URL链接来注入CSS,正在下面的代码中工作,如果我将CSS文件存储在项目的Bundle路径中,则为懒惰的webView:WKWebView = {Guard let path = Bundle.main.path(...

css ios swift wkwebview evaluatejavascript
2个回答
0
投票

您可以像其他任何文件类型一样下载远程css文件。


0
投票

感谢人们的建议,>>

找到了通过使用CSS文件的URL将CSS文件应用于webview

© www.soinside.com 2019 - 2024. All rights reserved.