最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

objective c - How to received alert() action from javascript into Cocoa application via WebView - Stack Overflow

programmeradmin1浏览0评论

I was develop 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 ?

I was develop 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 ?

Share Improve this question edited Jul 3, 2011 at 18:57 meddlesome asked Jul 3, 2011 at 18:50 meddlesomemeddlesome 5517 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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 es 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)

  1. 暂无评论