Monday, August 15, 2011

Mac OS - Opening a new browser window from within a WebKit WebView

If you Google "createWebViewWithRequest", "WebView open new window", "decidePolicyForNewWindowAction" or check out the Apple Developer Documentation on Opening Multiple Windows using WebKit, there is a lot of chatter on the difficulty of getting such a supposedly simple thing to occur.

The objective is this: You programmatically create a WebView and load standard HTML/JavaScript/CSS into it. You want to click on a link in your WebView which launches a new browser window to any URL of your choosing.

Amazingly, I haven't seen a single post that gave a simple answer to such a simple question...

Here it is in a nutshell:
  • No, you don't need to specify the WebPolicyDelegate as follows:
    @interface MyIAppDelegate : NSObject <NSApplicationDelegate, WebPolicyDelegate> {
    Some delegate are assumed and don't need to be declared. In fact, you get a compiler error if you try
  • Create your WebView in IB, add this line to MyAppDelegate:
    @property (assign) IBOutlet WebView *webView;
    and "connect" the IBAction to IB
  • In applicationDidFinishLaunching:, add this line:
    [webView setPolicyDelegate:self];
  • Add this delegate method:
    - (void)webView:(WebView *)webView decidePolicyForNewWindowAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request newFrameName:(NSString *)frameName decisionListener:(id < WebPolicyDecisionListener >)listener {
        [[NSWorkspace sharedWorkspace] openURL:[request URL]];
    }
  • In the HTML file, make sure your anchor tags contain 'target="_blank"'. For example:
    <a href="http://www.google.com/" target="_blank">click on this link</a>
You should be able to compile, click on a link in your WebView, and have it launch a new browser window to Google.