18

WKWebview でリクエストを監視するにはどうすればよいですか?

NSURLprotocol (canInitWithRequest) を使用してみましたが、ajax リクエスト (XHR) は監視されず、ナビゲーション リクエスト (ドキュメント リクエスト) のみが監視されます。

4

4 に答える 4

34

最後に私はそれを解決しました

Web ビューのコンテンツを制御できないため、jQuery AJAX 要求リスナーを含む Java スクリプトを WKWebview に挿入しました。

リスナーがリクエストをキャッチすると、ネイティブ アプリにメソッド内のリクエスト ボディを送信します。

webkit.messageHandlers.callbackHandler.postMessage(data);

ネイティブ アプリは、次のデリゲートでメッセージをキャッチします。

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

対応するアクションを実行します

関連するコードは次のとおりです。

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];
}
于 2015-03-03T09:40:44.903 に答える