斯威夫特:注入JS& CSS到WKWebView不起作用

时间:2017-05-17 06:47:15

标签: ios swift uiwebview wkwebview

我想尝试将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()
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

使用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;
}

答案 1 :(得分:0)

迅速5:

在Show WebSite之前,将CSS注入html

.gitlab-ci.yml

答案 2 :(得分:-3)

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