美文网首页
WKWebView JS交互

WKWebView JS交互

作者: 114105lijia | 来源:发表于2019-10-12 11:00 被阅读0次

直接上代码:

#import "MINISO_News_ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>
#import "MINISO_News_Back_View.h"

@interface MINISO_News_ViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property (nonatomic, strong) NSString *firstUrl;
@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)WKUserContentController *userContentController;

@property (nonatomic, strong) MINISO_News_Back_View *backView;

@end

@implementation MINISO_News_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"资讯";
    self.view.backgroundColor = RGBCOLOR(241, 241, 241);
    
    [self createWK];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)createWK {
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        
        // 为WKWebViewConfiguration设置偏好设置
        WKPreferences *preferences = [[WKPreferences alloc] init];
        configuration.preferences = preferences;
        
        // 允许native和js交互
        preferences.javaScriptEnabled = YES;
        
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        [userContentController addScriptMessageHandler:self name:@"event"];
        configuration.userContentController = userContentController;
        self.userContentController = userContentController;
        
        // 初始化webview
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, Height_StatusBar, MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT - Height_TabBar - Height_StatusBar) configuration:configuration];
        [self.view addSubview:_webView];
        NSURL *url = [NSURL URLWithString:self.firstUrl];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [_webView loadRequest:request];
        
        [self createBackBtn];
    }
}

- (void)createBackBtn {
    _backView = [MINISO_News_Back_View instanceView];
    [self.view addSubview:_backView];
    _backView.frame = CGRectMake(0, MAINSCREEN_HEIGHT - Height_TabBar - 44, MAINSCREEN_WIDTH, 44);
    _backView.hidden = YES;
    MINISOWeakSelf;
    _backView.clickLeftBlock = ^(BOOL isLeft) {
        [weakSelf clickLeft:isLeft];
    };
}

- (void)clickLeft:(BOOL)isLeft {
    if (isLeft) {
        if ([_webView canGoBack]) {
//            WKNavigation *back = [_webView goBack];
            WKBackForwardListItem *item1 = [self.webView.backForwardList itemAtIndex:-1];
            [self.webView goToBackForwardListItem:item1];
        }
    } else {
        if ([_webView canGoForward]) {
//            [_webView goForward];
            WKBackForwardListItem *item1 = [self.webView.backForwardList itemAtIndex:1];
            [self.webView goToBackForwardListItem:item1];
        }
    }
}

- (void)updateBackAndForward {
    _backView.left_select = [_webView canGoBack];
    _backView.right_select = [_webView canGoForward];
    
    if (_backView.left_select || _backView.right_select) {
        _backView.hidden = NO;
        _webView.height = MAINSCREEN_HEIGHT - Height_TabBar - Height_StatusBar - 44;
    } else {
        _backView.hidden = YES;
        _webView.height = MAINSCREEN_HEIGHT - Height_TabBar - Height_StatusBar;
    }
}

- (NSString *)firstUrl {
    return @"https://m.cbndata.com/information";
}

#pragma mark - WKUIDelegate
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    
    //如果点击某个按钮时,跳转的是其他链接,必须加上这个代理方法,不然点击无效  比如链接里面左侧菜单栏-星数
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [MINISOCommonLoadingView showToSuperview:self.view];
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [MINISOCommonLoadingView hideToSuperview:self.view];
    
    //屏蔽标签
    [self jsInteraction];
    
    //实时更新前进和返回状态
    [self updateBackAndForward];
}

- (void)jsInteraction {
    NSMutableString *s = [NSMutableString string];
    [s appendFormat:@"document.getElementById('message-btn').remove();"];
    [s appendFormat:@"var ul = document.getElementsByClassName('main-nav-category')[0];"];
    [s appendFormat:@"var li_list = ul.childNodes;"];
    [s appendFormat:@"li_list[3].remove();"];   //删除活动
    //删除活动后,星数上移,所以星数的索引还是3,    注册一样
    [s appendFormat:@"li_list[3].remove();"];   //删除星数
    [s appendFormat:@"li_list[3].remove();"];   //删除注册
    [s appendFormat:@"document.getElementsByClassName('report-controller not-pxtorem')[0].remove();"];
    
    [_webView evaluateJavaScript:s completionHandler:^(id _Nullable respons, NSError * _Nullable error) {
//        NSLog(@"---success");
    }];
}

-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [MINISOCommonLoadingView hideToSuperview:self.view];
    [_webView reload];
}

#pragma mark - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"%@,%@",message.name,message.body);
}

-(void)dealloc{
    // 必须和add一起出现,否则导致内存泄漏
    [self.userContentController removeScriptMessageHandlerForName:@"event"];
}

@end

相关文章

网友评论

      本文标题:WKWebView JS交互

      本文链接:https://www.haomeiwen.com/subject/znfqmctx.html