阻止来自 WKWebView 中加载的 url 的广告 [英] block ads from url loaded in WKWebView

查看:73
本文介绍了阻止来自 WKWebView 中加载的 url 的广告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 webView 中加载 url,现在我想阻止来自 webView 中 url 的广告.我怎样才能做到这一点?

I am loading url in webView and now I want to block ads from url in webView. How can I achieve this?

[_webVw loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:page_url]]];

推荐答案

假设您不介意向 iOS 10 或更早版本投放广告,那么 iOS 11 及更高版本包含内容阻止规则.

Assuming you don't mind ads being served to iOS 10 or earlier, then iOS 11 and later include content blocking rules.

假设我有一个 UIViewController 子类,它有一个 webView 属性指向我的 WKWebView 实例.我实现了一个名为 goHome 的自定义方法,它访问一些定义的主页"网址.不过,在执行此操作之前,我可能希望将内容阻止规则加载到我的 Web 视图中.我从这样的事情开始:

Suppose I have a UIViewController subclass which has a webView property pointing to my WKWebView instance. I implement a custom method called goHome which visits some defined "home" URL. Before I do this, though, I might want to load content blocking rules into my web view. I get things started with something like this:

- ( void ) viewDidLoad
{
    [ super viewDidLoad ];

    // (other setup stuff here...)

    [ self reloadContentBlockingRulesAndGoHome ];
}

如果我使用的是 iOS 11 或更高版本,重新加载阻止规则"内容会加载规则.如果您需要对其他版本的 iOS 的支持,请参阅其他答案.请原谅这里的空白布局古怪,当涉及到在参数中包含块的 Objective C 消息时,我有一种古怪的编码风格:

The 'reload blocking rules' stuff loads rules if I'm on iOS 11 or later. If you need support for other versions of iOS, see other answers. Forgive the white space layout oddities here, I have a quirky coding style when it comes to Objective C messages that include blocks in the parameters:

- ( void ) reloadContentBlockingRulesAndGoHome
{
    if ( @available( iOS 11, * ) )
    {
        [
            WKContentRuleListStore.defaultStore
                compileContentRuleListForIdentifier: @"ContentBlockingRules"
                             encodedContentRuleList: @"...see below!..."
                                  completionHandler: ^ ( WKContentRuleList * ruleList, NSError * error )
            {
                [ super viewDidLoad ];

                if ( error == nil )
                {
                    [ self.webView.configuration.userContentController addContentRuleList: ruleList ];
                    [ self goHome ];
                }
            }
        ];
    }
    else
    {
        [ self goHome ];
    }
}

那个 encodedContentRuleList 参数采用 JSON 字符串.为了清楚起见,我倾向于将其放在自己的方法中,因此上面的代码实际上可能会说:

That encodedContentRuleList parameter takes a JSON string. I tend to put that in its own method for clarity, so the code above might actually say:

[ WKContentRuleListStore.defaultStore
     compileContentRuleListForIdentifier: @"ContentBlockingRules"
                  encodedContentRuleList: [ self contentBlockingRules ]
                       completionHandler: ^ ( WKContentRuleList * ruleList, NSError * error ) { ... } ];

那么 [ self contentBlockingRules ] 会做什么?那只是返回一个 NSString 给出内容阻塞数据.在不与某种第三方广告拦截服务集成的情况下,您所能做的就是检查感兴趣的各个页面并开始注意包含广告的 HTML 元素的常见类名或 ID,以及通知(例如来自 Safari Web 检查器的网络"选项卡) 从中提取广告材料的所有域.一旦您意识到现在一个典型的网站中包含了多少广告材料,这是一个启发性的过程,虽然有些令人沮丧.

So what would [ self contentBlockingRules ] do? That just returns an NSString giving the content blocking data. Without integrating with some kind of third party ad block service, all you can do is inspect individual pages of interest and start noticing common class names or IDs of HTML elements that contain adverts, plus notice (from e.g. the Safari Web inspector's "Network" tab) all the domains from which advertising material is pulled. It's an illuminating, if somewhat depressing process, once you realise just how much advertising material is included on a typical web site now.

仔细阅读:

这是一个示例,其中包含一些 CSS 选择器阻止内容、阻止来自服务器本身的特定 URL(例如,他们可能自己提供的某些自定义广告代码),以及您想要阻止的通用第三方域的一些规则(我使用这些很多).

Here's an example that includes some CSS selector blocking stuff, blocks a particular URL from the server itself (e.g. some custom ad code they might be serving themselves), plus some rules for generalised third party domains you want to block (I use these a lot).

- ( NSString * ) contentBlockingRules
{
    return @" \
    [ \
      { \
        \"trigger\": { \
          \"url-filter\": \".*\" \
        }, \
        \"action\": { \
          \"type\": \"css-display-none\", \
          \"selector\": \".some_css_class, .some_other_class, #some_css_id\" \
        } \
      }, \
      { \
        \"trigger\": { \
          \"url-filter\": \"\\/some\\/very-specific-filename\\\\.js\", \
          \"resource-type\": [ \"script\" ] \
        }, \
        \"url-filter-is-case-sensitive\": true, \
        \"action\": { \
          \"type\": \"block\" \
        } \
      }, \
      { \
        \"trigger\": { \
          \"url-filter\": \".*\", \
          \"if-domain\": [ \"doubleclick.net\", \"adservice.google.com\", \"etc\" ], \
          \"resource-type\": [ \"script\" ] \
        }, \
        \"action\": { \
          \"type\": \"block\" \
        } \
      } \
    ]";
}

将 JSON 编码为 NSString 是一件令人讨厌的事情——正如你所看到的,结果是混乱的,有大量的转义正在进行,特别是对于一些 URL 部分,它们为 JSON 转义一次,然后再次转义为NSString 文字.可能有更简洁的方法可以更轻松地维护 JSON 数据.

It's nasty taking JSON and encoding it into an NSString - as you can see, the result is messy with an awful lot of escaping going on, especially for some of the URL parts which are escaped once for JSON, then escaped again for the NSString literal. There are probably cleaner ways to do this that make maintenance of the JSON data much easier.

由于许多网站上的广告和跟踪代码数量庞大,因此阻止内容时页面加载速度的差异可能会非常大.为您的用户提供更好的体验并减少他们的移动数据流量是值得的,但是:

Due to the sheer volume of advertising and tracking code on many sites, the difference in page load speed when you block stuff can be dramatic. It's worth the effort to give your users a better experience and hit their mobile data less, BUT:

  • 您可能在访问的网站上违反了服务条款和条件
  • 如果网站更新了它们的代码,那么您最终可能会错过一些您打算屏蔽的广告
  • 网站更新或过于笼统的阻止规则可能会意外隐藏合法"的非广告页面内容的风险稍大一些.

不要只是复制和粘贴上面的任何内容,而是请仔细阅读有关上述各种技术和框架方法的 Apple 开发人员文档,以便您了解限制、错误处理要求等.上面的例子只是让你开始了解概念,但从完全理解你正在做的事情的角度编写真正的代码很重要 - 你的应用用户应该得到稳定的体验:-)

Rather than just copy and paste anything above, please instead carefully read the Apple Developer Documentation on the various techniques and framework methods above, so that you understand limitations, error handling requirements and so-forth. The above examples are just to get you started on the concepts, but it's important to write real code from a position of fully understanding the things you are doing - your app users deserve a stable experience :-)

这篇关于阻止来自 WKWebView 中加载的 url 的广告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆