似乎有一个错误,webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:
即请求总是nil
,但是有一个强大的解决方案可以同时使用普通target="_blank"
链接和 javascript 链接。
基本上,我使用另一个短暂的 WebView 来处理新页面的加载。类似于 Yoni Shalom,但语法糖多一点。
要使用它,首先为您的 WebView 设置一个委托对象,在这种情况下,我将自己设置为委托:
webView.UIDelegate = self;
然后只需实现webView:createWebViewWithRequest:
委托方法并在加载新页面时使用基于块的 API 执行某些操作,在这种情况下,我在外部浏览器中打开页面:
-(WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
return [GBWebViewExternalLinkHandler riggedWebViewWithLoadHandler:^(NSURL *url) {
[[NSWorkspace sharedWorkspace] openURL:url];
}];
}
差不多就是这样。这是我的课程的代码。标题:
// GBWebViewExternalLinkHandler.h
// TabApp2
//
// Created by Luka Mirosevic on 13/03/2013.
// Copyright (c) 2013 Goonbee. All rights reserved.
//
#import <Foundation/Foundation.h>
@class WebView;
typedef void(^NewWindowCallback)(NSURL *url);
@interface GBWebViewExternalLinkHandler : NSObject
+(WebView *)riggedWebViewWithLoadHandler:(NewWindowCallback)handler;
@end
实施:
// GBWebViewExternalLinkHandler.m
// TabApp2
//
// Created by Luka Mirosevic on 13/03/2013.
// Copyright (c) 2013 Goonbee. All rights reserved.
//
#import "GBWebViewExternalLinkHandler.h"
#import <WebKit/WebKit.h>
@interface GBWebViewExternalLinkHandler ()
@property (strong, nonatomic) WebView *attachedWebView;
@property (strong, nonatomic) GBWebViewExternalLinkHandler *retainedSelf;
@property (copy, nonatomic) NewWindowCallback handler;
@end
@implementation GBWebViewExternalLinkHandler
-(id)init {
if (self = [super init]) {
//create a new webview with self as the policyDelegate, and keep a ref to it
self.attachedWebView = [WebView new];
self.attachedWebView.policyDelegate = self;
}
return self;
}
-(void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
//execute handler
if (self.handler) {
self.handler(actionInformation[WebActionOriginalURLKey]);
}
//our job is done so safe to unretain yourself
self.retainedSelf = nil;
}
+(WebView *)riggedWebViewWithLoadHandler:(NewWindowCallback)handler {
//create a new handler
GBWebViewExternalLinkHandler *newWindowHandler = [GBWebViewExternalLinkHandler new];
//store the block
newWindowHandler.handler = handler;
//retain yourself so that we persist until the webView:decidePolicyForNavigationAction:request:frame:decisionListener: method has been called
newWindowHandler.retainedSelf = newWindowHandler;
//return the attached webview
return newWindowHandler.attachedWebView;
}
@end
许可为 Apache 2。