iOS WKWebView與js交互

WKWebView在執行內存上圓圓高于UIWebView

不多說直接上代碼

不管是移除網頁內容,還是給圖片,按鈕添加點擊,都是一個套套路,找節點,如果不會找節點,Web開發會

#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController ()<WKNavigationDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    webView.navigationDelegate = self;
    [self.view addSubview:webView];
    NSURL *url = [NSURL URLWithString:@"http://m.dianping.com/tuan/deal/5501525"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}


/*
 *
 *  頁面加載完成時候調用   JS注入
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    NSMutableString *MString = [NSMutableString string];
    
    // 刪除網頁內不需要的內容
    
    //1. 頂部的返回 --> 起名字 結尾要加;
    [MString appendFormat:@"var headerTag = document.getElementsByTagName('header')[0];"];
    //刪除時需要找到父標簽 --> 自己干掉自己, 下不去手
    //parentNode:父標簽
    //removeChild:移除子標簽內容
    [MString appendFormat:@"header.parentNode.removeChild(header);"];
    [MString appendFormat:@"var buy  = document.getElementsByClassName('buy-now ')[0];"];
    [MString appendFormat:@"buy.parentNode.removeChild(buy);"];
    
    //給image添加點擊事件
    [MString appendString:@"var imgTag = document.getElenmentsByTagName('figure')[0].children[0];imgTag.onclick=function imgClick(){window.location.];
    
    
    [webView evaluateJavaScript:MString completionHandler:nil];
}
/*
 *
 *  網頁即將開始時候調用,攔截標簽點擊發送的請求
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{

    NSString *urlString = navigationAction.request.URL.absoluteString;
    NSLog(@"%@",urlString);
    
    if ([urlString isEqualToString:@"https://www.baidu.com"]) {
        
        //fuck come fuck go
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

@end

!!!!!!!以上是oc調用js.下面來js調用oc!!!!!!

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import <XLPhotoBrowser+CoderXL/XLPhotoBrowser.h>

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<WKUIDelegate,WKScriptMessageHandler>

@property (strong, nonatomic)   WKWebView                   *webView;
@property (strong, nonatomic)   UIProgressView              *progressView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"圖片下載測試";
    
    //初始話WKWebView
    [self initWKWebView];
    
    //初始化進度條
    [self initProgressView];
    //
    //添加進度條監聽
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

- (void)initWKWebView{
    
    //進行配置控制器
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
    //實例化對象
    configuration.userContentController = [WKUserContentController new];
    
    [configuration.userContentController addScriptMessageHandler:self name:@"imgClick"];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 40.0;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
    
    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"saner.html" ofType:nil];
    NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    
}


- (void)initProgressView{
    
    CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
    progressView.tintColor = [UIColor redColor];
    progressView.trackTintColor = [UIColor lightGrayColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
}


#pragma mark - KVO
// 計算wkWebView進度條
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

//當把JS返回給控制器,然后彈窗就是這樣設計的
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    NSLog(@"%@",message);
    completionHandler();
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    if ([message.name isEqualToString:@"imgClick"]) {
        [self downImage:message.body[@"url"]];
    }
}

-(void)downImage:(NSString *)url{
    
    NSArray *images = @[url];
    [XLPhotoBrowser showPhotoBrowserWithImages:images currentImageIndex:0];
    
}

html




<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf8">
            <script language="javascript">
            
            function imgClick() {
                window.webkit.messageHandlers.imgClick.postMessage({title:'張健標題',content:'張健內容',url:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1520591158463&di=31dc24992c2a5f6385c69e0b901604bd&imgtype=0&src=http%3A%2F%2Fh.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F55e736d12f2eb938e41eb7d7d9628535e5dd6fa0.jpg'});
            }


                </script>
            </head>
    
    <body>
        <input type="button" value="掃一掃" onclick="imgClick()" />

    </body>
</html>

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

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • 前言 關于UIWebView的介紹,相信看過上文的小伙伴們,已經大概清楚了吧,如果有問題,歡迎提問。 本文是本系列...
    CoderLF閱讀 9,010評論 2 12
  • 前言 在前面的文章中,我們介紹了UIWebView、WKWebView一些使用,與JS的交互和一些坑,相信看過的小...
    Dark_Angel閱讀 13,798評論 42 188
  • 在之前寫的一篇《產品經理第二節課,干貨來了》中,我很認真的將筆記整理出來,然后把95%左右的內容都分享了出來,可是...
    Blackmax閱讀 441評論 6 8
  • 今天是平安夜,據說,平安夜的晚上要吃一個蘋果以保平安。我不知道一定要吃蘋果的原因是什么,或許只是單純的“平”字諧音...
    堅持的考拉閱讀 264評論 0 0