- @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:@"提示信息" message:message delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
- [customAlert show];
- }
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//獲取js寫的界面的title
NSString *title = [_webVIew stringByEvaluatingJavaScriptFromString:@“document.title"];
//導航欄上顯示獲取的titile
lable.text = title;
/*解決webview上內嵌的頁面中彈出來的alert有域名問題!*/ PS:這個纔是這篇博客的關鍵
//1、獲取js的執行環境
JSContext *ctx = [webView valueForKeyPath:@“documentView.webView.mainFrame.javaScriptContext"];
//2、js那邊寫的提示框的函數入口,這裏差不多有點重寫那個函數的意思。JSValue *message參數可以獲取到js中的提示信息,OC中需要轉換爲string顯示出來,好了完成了。
ctx[@"window"][@"alert"] = ^(JSValue *message) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[message toString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
};
}