如何在WKWebview上监控请求?

Ben*_*ler 14 javascript monitor nsurlprotocol ios wkwebview

如何在WKWebview上监控请求?

我尝试过使用NSURLprotocol(canInitWithRequest)但它不会监视ajax请求(XHR),只监视导航请求(文档请求)

Ben*_*ler 33

最后我解决了

由于我无法控制Web视图内容,因此我向WKWebview注入了一个包含jQuery AJAX请求侦听器的java脚本.

当侦听器捕获请求时,它会在方法中向本机app发送请求正文:

webkit.messageHandlers.callbackHandler.postMessage(data);
Run Code Online (Sandbox Code Playgroud)

本机应用程序在名为的委托中捕获消息:

(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
Run Code Online (Sandbox Code Playgroud)

并执行相应的操作

这是相关代码:

ajaxHandler.js -

//Every time an Ajax call is being invoked the listener will recognize it and  will call the native app with the request details

$( document ).ajaxSend(function( event, request, settings )  {
    callNativeApp (settings.data);
});

function callNativeApp (data) {
    try {
        webkit.messageHandlers.callbackHandler.postMessage(data);
    }
    catch(err) {
        console.log('The native context does not exist yet');
    }
}
Run Code Online (Sandbox Code Playgroud)

我的ViewController委托是:

@interface BrowserViewController : UIViewController <UIWebViewDelegate, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIWebViewDelegate>
Run Code Online (Sandbox Code Playgroud)

而在我viewDidLoad(),我正在创建一个WKWebView:

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
[self addUserScriptToUserContentController:configuration.userContentController];
appWebView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:configuration];
appWebView.UIDelegate = self;
appWebView.navigationDelegate = self;
[appWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: @"http://#############"]]];                                                     
Run Code Online (Sandbox Code Playgroud)

这是addUserScriptToUserContentController:

- (void) addUserScriptToUserContentController:(WKUserContentController *) userContentController{
    NSString *jsHandler = [NSString stringWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"ajaxHandler" withExtension:@"js"] encoding:NSUTF8StringEncoding error:NULL];
    WKUserScript *ajaxHandler = [[WKUserScript alloc]initWithSource:jsHandler injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
    [userContentController addScriptMessageHandler:self name:@"callbackHandler"];
    [userContentController addUserScript:ajaxHandler];
}
Run Code Online (Sandbox Code Playgroud)


use*_*282 7

@Benzi Heler的答案很好,但是它使用的jQuery似乎不再可用WKWebView,因此我找到了不使用jQuery的解决方案。

这是ViewController的实现,通过该实现,您可以通过通知每个AJAX请求的完成WKWebView

import UIKit
import WebKit

class WebViewController: UIViewController {

    private var wkWebView: WKWebView!
    private let handler = "handler"

    override func viewDidLoad() {
        super.viewDidLoad()

        let config = WKWebViewConfiguration()
        let userScript = WKUserScript(source: getScript(), injectionTime: .atDocumentStart, forMainFrameOnly: false)
        config.userContentController.addUserScript(userScript)
        config.userContentController.add(self, name: handler)

        wkWebView = WKWebView(frame:  view.bounds, configuration: config)
        view.addSubview(wkWebView)

        if let url = URL(string: "YOUR AJAX WEBSITE") {
            wkWebView.load(URLRequest(url: url))
        } else {
            print("Wrong URL!")
        }
    }

    private func getScript() -> String {
        if let filepath = Bundle.main.path(forResource: "script", ofType: "js") {
            do {
                return try String(contentsOfFile: filepath)
            } catch {
                print(error)
            }
        } else {
            print("script.js not found!")
        }
        return ""
    }
}

extension WebViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if let dict = message.body as? Dictionary<String, AnyObject>, let status = dict["status"] as? Int, let responseUrl = dict["responseURL"] as? String {
            print(status)
            print(responseUrl)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

相当标准的实现。有一个以WKWebView编程方式创建的。有从script.js文件加载的注入脚本。

最重要的部分是script.js文件:

var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    this.addEventListener("load", function() {
        var message = {"status" : this.status, "responseURL" : this.responseURL}
        webkit.messageHandlers.handler.postMessage(message);
    });
    open.apply(this, arguments);
};
Run Code Online (Sandbox Code Playgroud)

userContentController每次加载AJAX请求时,都会调用委托方法。我要经过statusresponseURL,因为这是我所需要的,但是您也可以获取有关请求的更多信息。以下是所有可用属性和方法的列表:https : //developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest

我的解决方案的灵感来自@John Culviner撰写的以下答案:https ://stackoverflow.com/a/27363569/3448282


Jus*_*ael 6

如果您可以控制内部的内容,则WkWebView可以使用window.webkit.messageHandlers每当您发出ajax请求时将消息发送到本机应用程序,该请求将作为WKScriptMessage可以由您指定为您的任何内容处理的内容接收WKScriptMessageHandler.消息可以包含您希望的任何信息,并将自动转换为Objective-C或Swift代码中的本机对象/值.

如果您无法控制内容,您仍然可以通过注入WKUserScriptajax请求并使用上述方法发回消息来注入自己的JavaScript .