阻止 WKWebView 中加载的 url 中的广告

Sha*_*eri 2 xcode objective-c adblock nsurlrequest wkwebview

我正在 webView 中加载 url,现在我想阻止 webView 中的 url 中的广告。我怎样才能实现这个目标?

[_webVw loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:page_url]]];
Run Code Online (Sandbox Code Playgroud)

Lad*_*d.c 5

您需要使用UIWebViewDelegate中的webView:shouldStartLoadWithRequest:navigationType:方法,并使用要阻止的 URL 黑名单进行验证。如果您想要灵感或类似的过程,您可以查看这个库Ad Blocker iOS

- - 编辑 - -

这是我从 NSString 拦截广告 WKWebView 的代码。

//
//  ViewController.m
//  WKWebView
//
//  Created by Carlos Landaverde on 6/21/18.
//

#import "ViewController.h"

#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]

static NSString *rexKey1 = @"rexKey1";

@interface ViewController () <WKNavigationDelegate, WKUIDelegate>
@property (nonatomic) WKWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor: [UIColor whiteColor]];

    dispatch_group_t dispatchGroup = dispatch_group_create();
    __weak typeof(self) weakSelf = self;

    [NSUserDefaults.standardUserDefaults registerDefaults: @{ rexKey1: @NO }];
    [NSUserDefaults.standardUserDefaults synchronize];

    _webView = [[WKWebView alloc] initWithFrame: self.view.bounds];
    [_webView setNavigationDelegate: self];
    [_webView setUIDelegate: self];
    [_webView setAllowsBackForwardNavigationGestures: YES];
    [self.view addSubview: _webView];

    // If you want to remove previous WKContentRuleList
    // [_webView.configuration.userContentController removeAllContentRuleLists];

    dispatch_group_enter(dispatchGroup);
    [self setupContentBlockFromStringLiteral: ^{
        dispatch_group_leave(dispatchGroup);
    }];

    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
        [weakSelf beginLoading];
    });
}

- (void)beginLoading
{
    NSURLRequest *urlReq = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: @"https://www.google.com"]];
    [_webView loadRequest: urlReq];
}

- (void)setupContentBlockFromStringLiteral: (void (^)(void))callback
{
    /*
     Or you can block from a JSON file
     */
    NSString *jsonStr = NSStringMultiline([{
        "trigger": {
            "url-filter": "://googleads\\\\.g\\\\.doubleclick\\\\.net.*"
        },
        "action": {
            "type": "block"
        }
    }]);

    if ([[NSUserDefaults.standardUserDefaults objectForKey: rexKey1] boolValue]) {
        [WKContentRuleListStore.defaultStore compileContentRuleListForIdentifier: rexKey1 encodedContentRuleList: jsonStr completionHandler: ^(WKContentRuleList *contentRuleList, NSError *err) {

            if (err != nil) {
                NSLog(@"Error on content rule list compiled");
                [NSUserDefaults.standardUserDefaults setObject: @NO forKey: rexKey1];
                return;
            }

            if (contentRuleList) {
                [_webView.configuration.userContentController addContentRuleList: contentRuleList];
                callback();
            }
        }];
    }
    else {
        [WKContentRuleListStore.defaultStore compileContentRuleListForIdentifier: rexKey1 encodedContentRuleList: jsonStr completionHandler: ^(WKContentRuleList *contentRuleList, NSError *err) {

            if (err != nil) {
                NSLog(@"Error on content rule list not compiled");
            }

            if (contentRuleList) {
                [_webView.configuration.userContentController addContentRuleList: contentRuleList];
                [NSUserDefaults.standardUserDefaults setObject: @YES forKey: rexKey1];
                callback();
            }
        }];
    }
}

@end
Run Code Online (Sandbox Code Playgroud)