相信你们都不陌生,这个在WebView delegate里有实现
贴一段代码web
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ request = [IBWebMethod formAuthorizationRequest:request]; return [IBWebMethod interceptRequest:request BaseViewController:self]; }
ture or false 来决定WebView 是否加载请求。
能够经过new NSURLRequest赋给原request来向request里添加自定义的信息(头或参数)
<!--more-->ajax
可是因为Ajax 请求不是刷新整个WebView,上面的方法中没法捕获。app
因而就想到了想到了经过注入js来pop 出Ajax事件来捕获。
StackOverFlow连接ide
var s_ajaxListener = new Object(); s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open; s_ajaxListener.tempSend = XMLHttpRequest.prototype.send; s_ajaxListener.callback = function () { console.log('mpAjaxHandler://' + this.url); window.location='mpAjaxHandler://' + this.url; }; s_ajaxListener.callbackDone = function (state,status) { console.log('mpAjaxHandlerDone://' + state + ':' + status + '/' + this.url); window.location='mpAjaxHandlerDone://' + state + ':' + status + '/' + this.url; }; // Added this function to catch the readyState changes and request // fake page loads. function override_onreadystatechange(){ s_ajaxListener.callbackDone(this.readyState); this.original_onreadystatechange(); } XMLHttpRequest.prototype.open = function(a,b) { if (!a) var a=''; if (!b) var b=''; s_ajaxListener.tempOpen.apply(this, arguments); s_ajaxListener.method = a; s_ajaxListener.url = b; if (a.toLowerCase() == 'get') { s_ajaxListener.data = b.split('?'); s_ajaxListener.data = s_ajaxListener.data[1]; } } XMLHttpRequest.prototype.send = function(a,b) { if (!a) var a=''; if (!b) var b=''; this.setCoustomHeader(); s_ajaxListener.tempSend.apply(this, arguments); if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a; s_ajaxListener.callback(); // Added this to intercept Ajax responses for a given send(). this.original_onreadystatechange = this.onreadystatechange; this.onreadystatechange = override_onreadystatechange; }
能够看到重写了XMLHttpRequest(Ajax)的open与send方法来pop出事件
在捕获的事件中从新指定了window.location来响应WebView的delegatepost
上代码性能
+ (NSString *)jsString:(NSString *)baseString{ return [NSString stringWithFormat:@"%@\n XMLHttpRequest.prototype.setCoustomHeader = function(){ this.setRequestHeader(\"Authorization\",\"%@\");}", baseString, [IBDataManager sharedManager].baseAuth]; }
一样利用js注入把咱们的头加入的Ajax请求中
达到了Ajax自定义header 与捕获的需求ui
iOS UIWebView 有很大的性能和内存泄漏的问题
能够考虑将UIWebView与WKWebView封装成一套API来调用this
最近在开发新的需求和重构代码,这段重构把WebView单独拿出来作成了一个BaseWebViewController,为下一步将UIWebView与WKWebView统一作准备。url