如何通过WebView从javascript到Cocoa应用程序接收alert()动作

med*_*ome 0 javascript cocoa objective-c webview

我正在开发一些Cocoa应用程序WebView.现在我可以使用来评估javascript到HTML文件evaluateWebScript:

但是我需要alert()从javascript 接收一个事件才能在Cocoa中显示NSAlertSheet.

可可开发怎么办?

Rob*_*ger 8

您需要设置一个对象作为WebUIDelegateWebView(使用setUIDelegate:方法),并在该对象实现?webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:委托方法.当一个页面加载到WebView调用alert()JavaScript函数时,将调用此方法.

在执行委托方法时,应显示警报.警报应该:

  1. 显示传入方法的确切消息字符串
  2. 表明该消息来自JavaScript
  3. 只包含一个按钮,一个OK按钮

这是一个基本的例子:

- (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];
}
Run Code Online (Sandbox Code Playgroud)