web页面不携带cookie实现自动登录

2017-07-24  本文已影响54人  时米高的人生笔记

需求背景

使用某个app的时候碰到一个web页面, 登录之后每次打开都还要重新登录. 想办法弄到url之后发现, 这个页面没有携带cookie. 所以, 就在想这种情况下有没办法实现自动登录.

实现思路

代码

-1. 加载webview

self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    NSURL *URL = [NSURL URLWithString:@"http://www.kball.com.cn:3000/huolala/tkb_huolala_insurance_reg.html?channelId=huolala"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    [self.webView loadRequest:request];

-2. 在webview加载完成的代理方法中, 执行js语句

//webview加载完成代理
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {

    //拼接js语句,用js语句自动填充账号和密码
    NSString *userPhone = @"18576677707";
    NSString *userPassWord = @"123456";
    NSString *javaScript = [NSString stringWithFormat:@"var x = document.getElementsByClassName('userPhone');var i;for (i = 0; i < x.length; i++) {x[i].value=%@;}var y = document.getElementsByClassName('userPassWord');var i;for (i = 0; i < y.length; i++) {y[i].value=%@;}" ,userPhone,userPassWord];
    
    //调用js方法
    [webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable sucess, NSError * _Nullable error) {
        //成功回调,调用登录方法
        [webView evaluateJavaScript:@"login()" completionHandler:^(id _Nullable sucess, NSError * _Nullable error) {      
        }];        
    }];
}

demo地址:

https://git.oschina.net/SLY_C/oc_jsJiaoHu_ZiDongDengLu.git

上一篇下一篇

猜你喜欢

热点阅读