iOS Webview 實現修改javascript confirm 和 alert


貼代碼:

@interface UIWebView (JavaScriptAlert)  
-(void) webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame;  
- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame;  
@end  
  
@implementation UIWebView (JavaScriptAlert)  
  
- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {  
    UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:@"助手提示" message:message delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];  
    [customAlert show];  
}  
static BOOL diagStat = NO;  
static NSInteger bIdx = -1;  
- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {  
    UIAlertView *confirmDiag = [[UIAlertView alloc] initWithTitle:@"助手提示"  
                                                          message:message  
                                                         delegate:self  
                                                cancelButtonTitle:@"取消"  
                                                otherButtonTitles:@"確定", nil nil];  
      
    [confirmDiag show];  
    bIdx = -1;  
      
    while (bIdx==-1) {  
        //[NSThread sleepForTimeInterval:0.2];  
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];  
    }  
    if (bIdx == 0){//取消;  
        diagStat = NO;  
    }  
    else if (bIdx == 1) {//確定;  
        diagStat = YES;  
    }  
    return diagStat;  
}  
  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{  
    bIdx = buttonIndex;  
}  
  
@end

關於WKWebView:

之前用WebView裝載一個網頁時,彈出Alert時會顯示網址,由於不想把網址暴露給用戶這樣顯示就不是很友好了。UIWebView文檔內沒有找到可以捕獲這類信息的API。GOOGLE了下發現了WKWebView組件,WKWebView是IOS8新推出的組件,目的是給出一個新的高性能的 Web View 解決方案,擺脫過去 UIWebView 的老舊笨重特別是內存占用量巨大的問題。以下為示例代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
//  ViewController.swift
//  KenWKWebView
//
//  Created by KenNgai on 10/10/15.
//  Copyright © 2015 IT. All rights reserved.
//
 
import  UIKit
import  WebKit  //導入WebKit  WKWebView應該是用Webkit內核
 
class  ViewController UIViewController , WKNavigationDelegate , WKUIDelegate  {
 
     var  wkBrowser : WKWebView !
     
     override  func  viewDidLoad () {
         super . viewDidLoad ()
         self . wkBrowser  WKWebView ( frame self . view . frame )
         //self.wkBrowser.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!))
         let  html  "<html><title>Dialog</title><style type='text/css'>body{font-size:60px}</style><script type='text/javascript'>function myconfirm(){if(confirm('Star it?')){alert('Done')}}</script><body><a href=\"javascript:alert('Just Alert')\" >Alert</a><br /><a href=\"javascript:myconfirm()\">Logout</a></body></html>"
         self . wkBrowser . loadHTMLString ( html baseURL nil )
         self . wkBrowser . navigationDelegate  self
         self . wkBrowser . UIDelegate  self
         self . view . addSubview ( wkBrowser )
     }
     
 
     override  func  didReceiveMemoryWarning () {
         super . didReceiveMemoryWarning ()
         // Dispose of any resources that can be recreated.
     }
 
}
 
//捕捉異常信息
private  typealias  wkNavigationDelegate  ViewController
extension  wkNavigationDelegate  {
     func  webView ( webView WKWebView didFailNavigation  navigation WKNavigation !,  withError  error NSError ) {
         NSLog ( error . debugDescription )
     }
     
     func  webView ( webView WKWebView didFailProvisionalNavigation  navigation WKNavigation !,  withError  error NSError ) {
         NSLog ( error . debugDescription )
     }
}
 
private  typealias  wkUIDelegate  ViewController
extension  wkUIDelegate  {
     //HTML頁面Alert出內容
     func  webView ( webView WKWebView runJavaScriptAlertPanelWithMessage  message String initiatedByFrame  frame WKFrameInfo completionHandler : () - >  Void ) {
         let  ac  UIAlertController ( title webView . title message message preferredStyle UIAlertControllerStyle . Alert )
         ac . addAction ( UIAlertAction ( title "Ok" style UIAlertActionStyle . Cancel handler : { ( a ) - >  Void  in
             completionHandler ()
         }))
         
         self . presentViewController ( ac animated true completion nil )
     }
     
     //HTML頁面彈出Confirm時調用此方法
     func  webView ( webView WKWebView runJavaScriptConfirmPanelWithMessage  message String initiatedByFrame  frame WKFrameInfo completionHandler : ( Bool ) - >  Void ) {
         let  ac  UIAlertController ( title webView . title message message preferredStyle UIAlertControllerStyle . Alert )
         ac . addAction ( UIAlertAction ( title "Ok" style UIAlertActionStyle . Default handler :
             { ( ac ) - >  Void  in
                 completionHandler ( true )   //按確定的時候傳true
         }))
         
         ac . addAction ( UIAlertAction ( title "Cancel" style UIAlertActionStyle . Cancel handler :
             { ( ac ) - >  Void  in
                 completionHandler ( false )   //取消傳false
         }))
         
         self . presentViewController ( ac animated true completion nil )
     }
}

 

如果你訪問的頁面的協議是https那么要在info.list同添加以下Key:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

具體可參考:https://lvwenhan.com/ios/460.html

 

鏈接:

iOS Webview 實現修改javascript confirm 和 alert

UIWebView 屏蔽 alert警告框

WKWebView捕獲HTML彈出的Alert和Confirm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM