iOS UIWebView原生与网页交互常用知识点

iOS WebView使用POST方式加载URL及传参
iOS WebView打开URL时会对地址自动进行URL

前言

在App开发中,绝对部分都会涉及到UIWebView/WKWebView内嵌网页的情况出现,因此常常会涉及到原生与网页的交互等相关处理

知识点:User-Agent、Cookie、NSURLProtocol、NSURLProtocol本地构造response、请求mock假数据、js自动跳转、referrer、

一、设置User-Agent

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];  
// 浏览器的默认user-agent
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];  

// 在原默认user-agent上拼接自定义数据
NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];  

// 将新拼接好的user-agent注册,浏览器就会在请求时带上这个user-agent,注册的这个步骤要在浏览器发起请求前才会对请求生效
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil nil];  
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

二、设置管理cookie

2.1 获取cookie

 NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];  
 // 获取制定路径下的cookie,以http://www.baidu.com为例
 NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString: @"http://www.baidu.com"]]; 
for (NSHTTPCookie  *cookie in cookieAry) {  
      // xxx 对获取到的cookie进行相关处理
 }  

2.2 删除cookie

NSHTTPCookie *cookie;  
      
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];  
      
    NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString: _urlstr]];  
      
    for (cookie in cookieAry) {  
          
        [cookieJar deleteCookie: cookie];  
          
    }

2.3 设置cookie

//设置cookie  
- (void)setCookie{  
      
    NSMutableDictionary *cookiePropertiesUser = [NSMutableDictionary dictionary];  
    [cookiePropertiesUser setObject:@"cookie_user" forKey:NSHTTPCookieName];  
    [cookiePropertiesUser setObject:uid forKey:NSHTTPCookieValue];  
    [cookiePropertiesUser setObject:@"xxx.xxx.com" forKey:NSHTTPCookieDomain];  
    [cookiePropertiesUser setObject:@"/" forKey:NSHTTPCookiePath];  
    [cookiePropertiesUser setObject:@"0" forKey:NSHTTPCookieVersion];  
      
    // set expiration to one month from now or any NSDate of your choosing  
    // this makes the cookie sessionless and it will persist across web sessions and app launches  
    /// if you want the cookie to be destroyed when your app exits, don't set this  
    [cookiePropertiesUser setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];  
      
    NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:cookiePropertiesUser];  
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser];  
} 

三、伪造Referrer、增加中间页空白跳转

业务需求:在接入一个第三方支付时,基本流程是生产一个订单,然后后端返回一个URL用浏览器打开,之后就是打开原生的微信或支付宝支付,但其中一家支付厂商的支付URL有个特殊的要求,就是在浏览器发起请求时要设置Referrer这个请求头,但当前这个请求本身是第一次请求,浏览器默认是的referrer事空的,必须要在客户端自己想办法加上。

  • 方法一,在webview发起的请求里添加相关header字段,无效
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
[requestM setValue:@"自定义Referer"  forHTTPHeaderField:@"Referrer"];     
[self.webView loadRequest:requestM];
  • 方法二,在UIWebView的代理里判断header,没有对应header,重新发起请求,结果无效
- (BOOL) webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType) navigationType{

// 判断当前请求是否包含了自定义header字段
BOOL headerIsPresent = [[request allHTTPHeaderFields] objectForKey:@"my custom header"]!=nil;
// 如果已经包含了直接运行请求
if(headerIsPresent) return YES;

// 没有包含请求的,重新构造请求并设置header的相关内容
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [request URL];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

        // set the new headers
        for(NSString *key in [self.customHeaders allKeys]){
            [request addValue:[self.customHeaders objectForKey:key] forHTTPHeaderField:key];
        }

        // reload the request
        [self loadRequest:request];
    });
});
return NO;
}
  • 方法三,请求Referrer的地址,使用NSURLProtocol拦截WebView的这个请求并构造一个本地数据中转,通过这个中转再跳转到目标地址,代码如下:

亲测使用有效

目标地址:https://www.baidu.com 要伪造的referrer地址:https://www.google.com
这两个地址在实际开发使用中需要根据需要做成参数动态使用

1、创建URLProtocol的子类
LHJumpProtocol.h

#import <Foundation/Foundation.h>
@interface LHJumpProtocol : NSURLProtocol
@end

LHJumpProtocol.m

#import "LHJumpProtocol.h"
static NSString * const URLProtocolHandledKey = @"URLProtocolHandledKey_jump";

@interface LHJumpProtocol()<NSURLConnectionDelegate>
@property (nonatomic, strong) NSURLConnection *connection;
@end
@implementation LHJumpProtocol
/*
 这个方法是决定这个 protocol 是否可以处理传入的 request 的如是返回 true 就代表可以处理,如果返回 false 那么就不处理这个 request 。
 */
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    //看看是否已经处理过了,防止无限循环
    if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
        return NO;
    }
    
    NSString *url = request.URL.absoluteString;
    // 只有请求的是中转的地址才处理
    if ([url isEqualToString:@"https://www.google.com"]) {
        return YES;
    }
   return NO;
}
   
/*
 这个方法主要是用来返回格式化好的request,如果自己没有特殊需求的话,直接返回当前的request就好了。如果你想做些其他的,比如地址重定向,或者请求头的重新设置,你可以copy下这个request然后进行设置
 */
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
   // xxx 可以在这里对request进行相关的设置参数,重定向等处理
    return mutableReqeust;
    
}
/**
 该方法主要是判断两个请求是否为同一个请求,如果为同一个请求那么就会使用缓存数据。通常都是调用父类的该方法
 */
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
{
    return [super requestIsCacheEquivalent:a toRequest:b];
}
- (void)startLoading
{
    
    NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
    //打标签,防止无限循环
    [NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];
    
   // 虚拟一般网络请求时服务器返回的中转网页内容,这段网页数据的作用是告诉浏览器请求都带上referrer,并且会加载这段网页后自动跳转到目标地址去
 NSString *targetUrl = @"http://www.baidu.com";
 NSString *text = [NSString stringWithFormat:@"<html> <META content=\"always\" name=\"referrer\"><script>try{if(window.opener&&window.opener.bds&&window.opener.bds.pdc&&window.opener.bds.pdc.sendLinkLog){window.opener.bds.pdc.sendLinkLog();}}catch(e) {};window.location.replace(\"%@\")</script> <noscript><META http-equiv=\"refresh\" content=\"0;URL='%@'\"></noscript></META></html>",targetUrl,targetUrl];
    
// 将字符串转换成NSData数据
 NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
 // 将数据构造成返回的response
 NSURLResponse *response = [[NSURLResponse alloc] initWithURL:mutableReqeust.URL MIMEType:@"text/html" expectedContentLength:data.length textEncodingName:nil];
    
    [self.client URLProtocol:self
          didReceiveResponse:response
          cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    
    [self.client URLProtocol:self didLoadData:data];
    [self.client URLProtocolDidFinishLoading:self];
    
}
- (void)stopLoading
{
    [self.connection cancel];
}
#pragma mark - NSURLConnectionDelegate

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.client URLProtocol:self didLoadData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self.client URLProtocol:self didFailWithError:error];
}

2、在AppDelegate里注册protocol

#import "LHAppDelegate.h"
#import "LHJumpProtocol.h"
@interface LHAppDelegate ()
@end
@implementation LHAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// xxxx 其他启动处理
// 注册protocol
[NSURLProtocol registerClass:[LHJumpProtocol class]];
    return YES;
}
@end

3、使用UIWebView发起请求

UIWebView *webView = [ [UIWebView alloc] iniwWithFrame:self.view.bounds];
// 这里请求的要是需要的referrer的地址,这样才能构造一个虚拟的referrer
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request];

四、js与原生交互

WebViewJavascriptBridge

参考文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容