How to display/handle a JavaScript alert in an OS X WebView?

440 views Asked by At

I have an OS X app that I am working on (technically implemented in RubyMotion, but that doesn't matter). The WebView wraps a web app that triggers a JavaScript alert before allowing you to perform an action. It works correctly in a normal web browser, but is not displayed in the WebView.

What configuration setting am I missing, or how can I handle this feature?

@web_view = WebView.alloc.initWithFrame(NSMakeRect(0, 0, 1000, 500))
@web_view.setAutoresizingMask(NSViewMinXMargin|NSViewMaxXMargin|NSViewMinYMargin|NSViewMaxYMargin|NSViewWidthSizable|NSViewHeightSizable)
@web_view.setMainFrameURL('http://localhost:3000')
@mainWindow.contentView.addSubview(@web_view)
1

There are 1 answers

0
Andrew On BEST ANSWER

In order to handle JavaScript alerts and confirmation dialog boxes, you need to specify the WebUIDelegate:

@web_view = WebView.alloc.initWithFrame(NSMakeRect(0, 0, 1000, 500))
@web_view.setUIDelegate(self)

...and implement these methods:

def webView(web_view, runJavaScriptAlertPanelWithMessage: message, initiatedByFrame: frame)
  alert = NSAlert.new
  alert.addButtonWithTitle("OK")
  alert.setMessageText(message)
  alert.runModal
end

def webView(web_view, runJavaScriptConfirmPanelWithMessage: message, initiatedByFrame: frame)
  result = NSRunInformationalAlertPanel("JavaScript", # title
                                        message,      # message
                                        "OK",         # default button
                                        "Cancel",     # alt button
                                        nil)
  NSAlertDefaultReturn == result
end