Swift:向WKWebView注入JS和CSS不起作用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift:向WKWebView注入JS和CSS不起作用相关的知识,希望对你有一定的参考价值。

我想尝试将js脚本注入WKWebView,但它不起作用。所以这是一个网络,但当它加载到应用程序时,我们应该隐藏页眉和页脚。我从配置中获取CSS URL并加载它并尝试将其与编写在代码上的JS一起注入。但是,网络已加载但预期的东西不起作用。怎么了?

这是代码(我省略了许多与问题无关的代码)

import UIKit
import WebKit

class CustomPageWebViewController: UIViewController, WKNavigationDelegate {

    private var webView: WKWebView = WKWebView()


    override func viewDidLoad() {
        super.viewDidLoad()

        webView.navigationDelegate = self
        view.addSubview(webView)

        // Request web page
        requestWebPage()

    }


    // MARK: - Request Web Page

    func requestWebPage() {
        if let urlString = URL(string: determineURLBasedOnPaymentName()) {
            webView.load(URLRequest(url: urlString))
        }
    }


    //

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        removeHeaderAndFooter(webView: webView)
    }

    func removeHeaderAndFooter(webView: WKWebView) {
        let cssURLString = ConfigManager.sharedInstance.cssURL
        if cssURLString != "" {
            let cssURL = URL(string: cssURLString)
            if let cssURL = cssURL {
                let sessionConfig = URLSessionConfiguration.default
                let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
                var request = URLRequest(url: cssURL)
                request.httpMethod = "GET"

                let task = session.dataTask(with: request, completionHandler: { (data: Data!, response: URLResponse!, error: Error!) -> Void in
                    if (error == nil) {
                        let result = String(data: data, encoding: String.Encoding.utf8)!

                        var js = "!function(){var e=document.createElement("style");e.type="text/css",e.innerhtml=window.atob(%@),document.getElementsByTagName("head")[0].appendChild(e);var t=document.createElement("style");t.type="text/css",t.innerHTML="#tab-hotel,#tabs-2,.rail-order__flex{display:none;} .search__label--input{height:45px;} #tabs-2{display:block;}",document.body.appendChild(t)}();"
                        // So after I get the CSS file from the link, I will inject it to the JS file here
                        js = String(format: js, result)

                        // And then inject the whole script to the webview
                        self.webView.evaluatejavascript(js, completionHandler: { (any, error) in

                        })
                    }
                })
                task.resume()
            }
        }
    }
}
答案

请使用UIWebView和webView.stringByEvaluatingJavaScript(来自:“”)

另一答案

使用WKUserScript处理WKWebview中的js消息处理程序执行

您可以通过链接WKUserScript not working中的答案来执行JS

这是我们在WKWebview中执行JS的方式

[objectofWKWebView evaluateJavaScript:yourScript completionHandler:^(id result, NSError *error) {}];

你可以创建WKWebView的类别并添加功能

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script {
__block NSString *resultString = nil;
__block BOOL finished = NO;

[self evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
    if (error == nil) {
        if (result != nil) {
            resultString = [NSString stringWithFormat:@"%@", result];
        }
    } else {
        NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
    }
    finished = YES;
}];

while (!finished)
{
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

return resultString;
}
另一答案

斯威夫特5:

在显示WebSite之前将CSS注入html

import UIKit
import WebKit

class WebViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        config()
    }

    private func config(){

        webView.navigationDelegate = self

        guard let url = URL(string: "url") else {
            return
        }

        webView.load(URLRequest(url: url))

    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        let css = "Css Code"
        let js = "var style = document.createElement('style'); style.innerHTML = '(css)'; document.head.appendChild(style);"
        webView.evaluateJavaScript(js, completionHandler: nil)
    }


}

以上是关于Swift:向WKWebView注入JS和CSS不起作用的主要内容,如果未能解决你的问题,请参考以下文章

将本地存储从 swift 注入到 WKWebview

从swift注入本地存储到WKWebview

在 WKwebView (SWIFT) 中加载本地资源以及 HTML 字符串?

WKWebView不显示提示框(Swift)

iOS开发漫话WKWebView之给H5网页图片添加点击事件以实现原生图片预览

利用WKWebView实现js与OC交互注意事项