开发者

How to received alert() action from javascript into Cocoa application via WebView

I was develop开发者_如何学JAVA some Cocoa application with WebView. Now I can evaluate javascript to HTML file by using evaluateWebScript:

But I need to receive an alert() event from javascript to display in Cocoa's NSAlertSheet.

How to do with cocoa development ?


You need to set an object as the WebUIDelegate of the WebView (using the setUIDelegate: method) and in that object implement the ‑webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame: delegate method. This method will be called when a page loaded into the WebView calls the alert() JavaScript function.

In your implementation of the delegate method, you should display an alert. The alert should:

  1. display the exact message string that is passed in to the method
  2. indicate that the message comes from JavaScript
  3. contain only one button, an OK button

Here is a basic example:

- (void)webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message
{
    NSAlert* jsAlert = [NSAlert alertWithMessageText:@"JavaScript"
                                       defaultButton:@"OK" 
                                     alternateButton:nil 
                                         otherButton:nil 
                           informativeTextWithFormat:@"%@", message];
    [jsAlert beginSheetModalForWindow:sender.window modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
}


You can try to override JavaScript alert function on window. In your custom alert you can redirect to predefined url, e.g. app://alert/something%32is%32wrong. That kind of redirect can be handled by UIWebView through webView:shouldLoadRequest:.

PS: I didn't try it :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜