【问题标题】:How to load CSS file by using URL in WKWebView如何在 WKWebView 中使用 URL 加载 CSS 文件
【发布时间】:2020-05-19 14:20:49
【问题描述】:

我想通过 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 文件。

【问题讨论】:

    标签: css ios swift wkwebview evaluatejavascript


    【解决方案1】:

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

    这是一个简单的例子(注意:只是一个例子!!! - 不打算成为生产代码!):

    func gotTheCSS(_ css: String) -> Void {
        print(css)
        // here is where you would inject it, just like you did when
        //  loading it from the bundle
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        DispatchQueue.global().async {
            if let url = URL(string: "http://yoursite.com/css/style.css") {
    
                do {
                    let cssString = try String(contentsOf: url, encoding: String.Encoding.utf8)
                    self.gotTheCSS(cssString)
                }
                catch {
                    print(error)
                }
    
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      感谢大家对我的问题的帮助/建议/回答。

      我找到了通过使用 CSS 文件的 URL 将 CSS 文件应用到 webview 的解决方案。

      将您的后端服务器链接用于 CSS 文件,例如,

          let cssURL = "https://xyz/styles/style.css" // Use your server css file url link
      

      然后是 JavaScript 注入问题,我将 JavaScript 注入代码 style 更改为 link,如下面的代码,我在 中编写的所有代码覆盖 func viewDidAppear(_ animated: Bool)" 方法,只需复制粘贴代码,它也会对你有用。

                  let source = """
                  var link = document.createElement('link');
                  link.href = '\(cssURL)';
                  link.rel= 'stylesheet'
                  document.head.appendChild(link);
                  """
                  let userScript = WKUserScript(source: source,
                                                injectionTime: .atDocumentEnd,
                                                forMainFrameOnly: true)
                  
                  let userContentController = WKUserContentController()
                  userContentController.addUserScript(userScript)
                  
                  let configuration = WKWebViewConfiguration()
                  configuration.userContentController = userContentController
                  
                  self.webView = WKWebView(frame: self.documentDiscriptionView.bounds,
                                           configuration: configuration)
                  self.webView.navigationDelegate = self
                  self.webView.scrollView.isScrollEnabled = false
                  self.webView.scrollView.bounces = false
                  
                  self.webView.isOpaque = false
                  self.webView.backgroundColor = UIColor.clear
                  self.webView.scrollView.backgroundColor = UIColor.clear
                  
                  self.self.webViewContainerView.addSubview( self.webView)
                  
          ///// Set Constraint
                  self.webView.translatesAutoresizingMaskIntoConstraints = false
                  self.webView.leadingAnchor.constraint(equalTo: self.webViewContainerView.leadingAnchor, constant: 0).isActive = true
                  self.webView.trailingAnchor.constraint(equalTo: self.webViewContainerView.trailingAnchor, constant: 0).isActive = true
                  self.webView.topAnchor.constraint(equalTo: self.webViewContainerView.topAnchor, constant: 0).isActive = true
                  self.webView.bottomAnchor.constraint(equalTo: self.webViewContainerView.bottomAnchor, constant: 0).isActive = true
      

      我的问题现在已经解决了,希望这个解决方案能帮助某人通过使用链接来应用 css,如果有人想要任何帮助将 CSS 应用到 webView,请告诉我,我很乐意提供帮助。

      【讨论】:

        猜你喜欢
        • 2019-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-24
        • 1970-01-01
        • 2020-05-22
        • 2016-04-08
        相关资源
        最近更新 更多