iOS 中WKWebView js 一種用法,移除廣告(標簽)

首先,我們要明確一個問題,在HTML中看到的每個內容都是用HTML標簽來描述并且由CSS來決定顯示的樣式的,因此,我們想隱藏(移除) HTML 中的具體內容主要有2種做法:
(1) 移除對應的html 標簽
(2)修改對應標簽的CSS 樣式

我們這里采用第二種,修改CSS 樣式來隱藏具體的內容,具體步驟如下:

要移除內容的網頁
  • 1 在Google Chrome 中打開對應的網頁,并打開網頁的開發者工具
    網頁開發者工具
  • 2 在網頁開發者工具中找到要隱藏(去除)的內容的 標簽,并驗證方法是否可行

    CSS 驗證想法

  • 3 在網頁開發者工具中用 js 語法驗證代碼是否可行

    js 驗證想法

  • 4 在手機上實現并驗證

    (1)創建WKWebView 設置代理 加載網頁

#import <WebKit/WebKit.h>


// 懶加載webview
-(WKWebView *)webView{
    
    if (!_webView) {
        _webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:[self webViewConfig]];
        
        // UI代理
        _webView.UIDelegate = self;
        
        //導航代理
        _webView.navigationDelegate = self;
        
        //是否允許手勢左滑返回上一級,類似導航控制器的左滑返回
        _webView.allowsBackForwardNavigationGestures = YES;
        
        [self.view addSubview:_webView];
        
    }
    return _webView;
    
}

(2) 加載網頁


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self webView];
    
   
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    
    NSString *urlStr = @"https://tieba.baidu.com/index.html";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [self.webView loadRequest:request];
    
}


(3) 在網頁加載完 點擊測試隱藏


- (IBAction)dismissBtnClick:(id)sender {
    
   NSString *jsStr = @"document.getElementsByClassName(\"index-forum-num-ten-millions\")[0].style.display='none'";
   [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable data, NSError * _Nullable error) {
       
       NSLog(@"-------error: %@",error);
   }];

}

(4)在網頁加載完 點擊測試恢復


- (IBAction)recoverBtnClick:(id)sender {
    
    NSString *jsStr = @"document.getElementsByClassName(\"index-forum-num-ten-millions\")[0].style.display=\"\"";
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        
        NSLog(@"-------error: %@",error);
    }];
    
}

最終效果


oc2jsgif.gif
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容