在iOS app 中经常会嵌套html 代码, 然后 js 的alert 的title 怎么修改呢,不修改的话很丑陋,用户无法接受。如下:
但是现在有了好的办法就是用 iOS native 的uiwebview 的扩展方法来监听 js的alert 然后自定义 alert 的title ,如下:
这样就可以自定义, 也比较好看了。
方法是 在 你加在webview 的 m 方法中加入:
@interface UIWebView (JavaScriptAlert) - (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame; @end @implementation UIWebView (JavaScriptAlert) - (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame { UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:@"我是JS Alert" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [customAlert show]; [customAlert release]; } @end
这样就ok了! 哈哈!
html 代码 :
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Webview document</title> <script type="text/javascript"> function change_header() { alert("不错的一天"); } </script> </head> <body style="background-color:transparent; color:white;"> <h4>UIWebView HTML document</h4> <button onclick="change_header()">按钮</button> </body> </html>