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:
- display the exact message string that is passed in to the method
- indicate that the message comes from JavaScript
- 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 :)
精彩评论