javascript - 我如何监控 WKWebview 上的请求?

标签 javascript ios monitor wkwebview nsurlprotocol

我如何监控 WKWebview 上的请求?

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

最佳答案

终于解决了

由于我无法控制 Web View 内容,我向 WKWebview 注入(inject)了一个包含 jQuery AJAX 请求监听器的 Java 脚本。

当监听器捕获请求时,它会在方法中向 native 应用程序发送请求正文:

webkit.messageHandlers.callbackHandler.postMessage(data);

native 应用程序在委托(delegate)中捕获消息:

(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message

并执行相应的 Action

相关代码如下:

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');
    }
}

我的 ViewController 代表是:

@interface BrowserViewController : UIViewController <UIWebViewDelegate, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIWebViewDelegate>

在我的 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://#############"]]];                                                     

这是 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];
}

关于javascript - 我如何监控 WKWebview 上的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28766676/

相关文章:

C#:强制监视器进入待机模式

winapi - 通过 Win32 API 或 NVidia API 启用/禁用多个显示器?

javascript - 如何使用ajax将js数组发送到servlet?

JavaScript try catch 语句

xcode - 通过链接到代码的外部目录在 XCode 中共享 ios 代码

iOS 键盘延迟动画

ios - DispatchQueue.main.async 阻塞主线程

linux - 女士监视器缺少事件,并显示其他多个

javascript - 执行了 ajax 请求。如何格式化返回的数据?

javascript - Node js错误: Cannot find module './lib/socket.io'