iOS Webkit跟踪单击使用的URL和URL方案

时间:2019-05-14 23:08:49

标签: ios objective-c uiwebview wkwebview

我试图将我的iOS UIWebview迁移到Webkit,但是我遇到了很多问题。我在webView:shouldStartLoadWithRequest:navigationType:中有一个代码,在此之前,我曾经像urls and url-scheem那样监视tell:, exit:, refresh:, mailto:,并确保只有自己的URL才能在WebView中打开。但是,尝试使用webkit来实现相同的方法行不通,请不确定是否在write方法中执行此操作,是否有人可以帮助我。

/ 尝试使用Webkit实施 /

- (BOOL)webView:(WKWebView *)inWeb decidePolicyForNavigationAction:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType{
    NSLog(@"Event: %@", @"shouldStartLoadWithRequest inType called");
    NSArray *schemeArray = @[@"share", @"map", @"rate", @"reload", @"exit"];
    NSString *url = [[inRequest URL] query];
    NSString *scheme = [[inRequest URL] scheme];
    NSString *StrPurl = [NSString stringWithFormat:@"%@",url];

    NSLog(@"[inRequest URL] == %@", StrPurl);
    NSLog(@"[inRequest NSURL] == %@", url);
    NSLog(@"[[inRequest URL] scheme] == %@", scheme);

    if ([StrPurl containsString:@"mysite.com"]){
        //coninue open
    }else if ( [schemeArray containsObject:[[inRequest URL] scheme]] ){
        //open share intent
        NSLog(@"Event: Share URL %@", [[inRequest URL] scheme]);
    }

    NSLog(@"Event: Request URL %@", url);
    return NO;
}

使用上面的示例在UIWebview中有效

- (BOOL)webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType{

    if (self.validatedRequest || inType != UIWebViewNavigationTypeLinkClicked){
        NSString *url = [[inRequest URL] query];
        NSString *scheme = [[inRequest URL] scheme];
        NSString *StrPurl = [NSString stringWithFormat:@"%@",url];

        NSLog(@"[inRequest URL] == %@", StrPurl);
        NSLog(@"[inRequest NSURL] == %@", url);
        NSLog(@"[[inRequest URL] scheme] == %@", scheme);
    }
}

我也有这种方法,但是当我单击tel:或其他外部URL时不会调用它

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"Event: %@", @"shouldStartLoadWithRequest navigationType called");
        //if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
        if (navigationAction.navigationType == UIWebViewNavigationTypeLinkClicked) {

        }
    NSString *url = [navigationAction.request.URL query];
    NSLog(@"Event: Request URL %@", url);
    decisionHandler(WKNavigationActionPolicyAllow);
}

1 个答案:

答案 0 :(得分:0)

尝试使用此委托方法:

- (void)webView:(WKWebView *)webView 
    decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction 
    decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

您需要致电NOdecisionHandler(WKNavigationActionPolicyAllow)而不是返回decisionHandler(WKNavigationActionPolicyCancel)

您可以使用NSURLRequest访问navigationAction.request

来源:https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455641-webview?language=objc