在UIWebView中驯服alert()

在UIWebView中调用alert()会弹出一个对话框,其中您的URL(主机名)作为Dialog标题,这很烦人。

这里讨论的方法很少(hacks)(http://stackoverflow.com/questions/10681381/change-javascript-alert-dialog-title-in-ios),但它们并不十分优雅。

随着JavaScriptCore的引入,我们可以通过JSContext用本地函数很好地替换警报函数。

 类ViewController:UIWebViewDelegate { 
 让webview:UIWebView! 
let alertFunction:@convention(block)字符串->无效= {(消息)// //#1
UIAlertView(标题:“本机警报”,消息:消息,委托:nil,cancelButtonTitle:“确定”).show()
}
  func viewDidLoad(){ 
webview.delegate =自我
}
  func webViewDidFinishLoad(webView:UIWebView){//#2 
if(webview.loading){return} //#3
让context = webview.valueForKeyPath(“ documentView.webView.mainFrame.javaScriptContext”)为! JSContext
context.exceptionHandler = {上下文,异常
打印(“ JS错误:\(例外)”
}
context.setObject(unsafeBitCast(alertFunction,AnyObject.self),forKeyedSubscript:“ alert”)
  //测试 
context.evaluateScript(“ alert('Test Message');”)
  } 
}
  1. alertFunction是我们的本机弹出功能。 在此示例中,我使用了不赞成使用的UIAlertView来简化演示。 您应该使用UIAlertController或自定义弹出窗口。
  2. 每次加载页面时,我们都需要执行此操作,因此代码进入UIWebViewDelegate函数webViewDidFinishLoad中。
  3. 由于webview可能多次调用webViewDidFinishLoad(ajax调用等),因此我们确保在webview.loading为true之后,代码仅执行一次。