让UIWebView中实现并控制弹出窗口

jopen 9年前

UIWebView本身不支持弹出窗口,然而有需求要用,不仅需要弹出窗口,而且需要在用户关闭窗口时触发一个javascript函数。研究了一下,没有使用任何第三方库实现了。
基本的思路是在UIWebView中拦截window.openwindow.close的调用。这里有2个技术问题:
1.如何在objective-c中改变javascript的行为?
我的思路是在页面加载完之后注入javascript。简单的说就是webViewDidFinishLoad中使用UIWebView 的stringByEvaluatingJavaScriptFromString注入javascript代码。
2.如何用javasript调用objective-c代码?
我使用URLScheme的方式来做。简单的来说,就是让定义2个URLScheme:
open://:用来出发弹出窗口;
back://:用来关闭窗口;后面可以跟一个参数,触发window.close之后需要回调的javascript函数;
然后在- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType中拦截URL请求就可以调用objective-c代码了。
具体的相关代码如下:
1.ViewController实现UIWebViewDelegate,在ViewDidLoad中将UIWebView的delegate设为自己:

_browser.delegate = self;

2.webViewDidFinishLoad中注入javascript

-(void) webViewDidFinishLoad:(UIWebView*)webView {      // this is a pop-up window      if (wvPopUp)      {            NSString *js = @"window.close = function () {window.location.assign(\"back://\" + window.location);};";          __unused NSString *jsOverrides = [webView                                            stringByEvaluatingJavaScriptFromString:js];      }else {        ///其他处理                NSString *js = @"window.open = function (url, d1, d2) { window.location = \"open://\" + url;        }";              __unused NSString *jsOverrides = [webView                                                stringByEvaluatingJavaScriptFromString:js];          }      }  }

3.在shouldStartLoadWithRequest中拦截URL请求

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{      NSString* requestURL = request.URL.absoluteString;        if ([requestURL rangeOfString:@"back://"].location == 0)          {              [self closePopup];              return NO;          } else if  ([requestURL hasPrefix: @"open://"]){                NSString *newUrl = [requestURL stringByReplacingOccurrencesOfString:@"open://" withString:@""];                NSURLRequest *newRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:newUrl]];              UIWebView *wv = [self popUpWebview];              [wv loadRequest:newRequest];              return NO;          }      return YES;    }

4.弹出窗口的objectie-c代码

- (UIWebView *) popUpWebview  {      // Create a web view that fills the entire window, minus the toolbar height      CGRect rect = CGRectMake(_browser.frame.origin.x+20,_browser.frame.origin.y+20,                               _browser.frame.size.width-40,_browser.frame.size.height-40);        vwPopUpContainer = [[UIView alloc] initWithFrame: rect];      vwPopUpContainer.backgroundColor = [UIColor grayColor];      [self.view addSubview:vwPopUpContainer];        CGRect rectBtn = CGRectMake(10, 10, 60, 20);      btnClosePopup = [[UIButton alloc] initWithFrame:rectBtn];         [btnClosePopup setTitle:@"Close" forState:UIControlStateNormal];      [btnClosePopup addTarget:self action:@selector(closePopup) forControlEvents:UIControlEventTouchUpInside];      [vwPopUpContainer addSubview:btnClosePopup];        CGRect rectWeb = CGRectMake(10, 40, rect.size.width - 20, rect.size.height - 50);        UIWebView *webView = [[UIWebView alloc]                            initWithFrame: rectWeb];        webView.scalesPageToFit = YES;      webView.delegate = self;        wvPopUp = webView;     [vwPopUpContainer addSubview:wvPopUp];      return webView;  }

5.关闭窗口处理包括回调触发带参数的javascript函数,这里函数名为onClosePopo

- (void) closePopup {      if (wvPopUp) {          NSURL *url = wvPopUp.request.URL;          NSString *surl = url.absoluteString;          NSUInteger pos = [surl rangeOfString:@"?"].location;          NSString *paras = @"";          if (pos != NSNotFound && pos < [surl length]-1) {              paras = [surl substringFromIndex:pos + 1];          }          NSString *js = [NSString stringWithFormat: @"onClosePopo('%@');",paras ];          __unused NSString *jsOverrides = [_browser                                            stringByEvaluatingJavaScriptFromString:js];            [wvPopUp removeFromSuperview];          wvPopUp = nil;      }      if(btnClosePopup){          [btnClosePopup removeFromSuperview];          btnClosePopup = nil;      }        if(vwPopUpContainer){          [vwPopUpContainer removeFromSuperview];          vwPopUpContainer = nil;      }  }

来自: http://www.jianshu.com/p/a149791d7e31