1. 利用 WKWebView 進行交互(系統 API)
2. 利用 UIWebView 進行交互(系統 API)
3. 蘋果的 javascriptcore.framework 框架
4. 跨平臺 cordova 框架
5. oc 第三方 webviewJavaScriptBridge
WKWebView 與 JS 交互實戰(zhàn)技巧
iOS8中引入的新組件矾缓,目的是給出一個新的高性能的 WEB查看解決方案锭亏,擺脫過去 UIWebView 老舊笨重特別是內存占用量巨大的問題。
進步
1. 將瀏覽器內核渲染進程體取出 App廉沮,由系統進行統一管理樟结,減少了相當一部分的性能損失
2. js 可以直接使用已經事先注入 js runtime 的 js 接口給原生層傳值拗军,不必再通過 iframe 制造頁面刷新再解析自定義協議
3. 支持高達60 fps 的滾動刷新頻率翠语,內置了手勢探測
?WKWebView API介紹
WKWebView 的頭文件聲明
// webview 配置韵卤,具體看下面
@property (nonatomic, readonly, copy) WKWebViewConfiguration *configuration;// 導航代理?
@property (nullable, nonatomic, weak) idnavigationDelegate;// 用戶交互代理
@property (nullable, nonatomic, weak) idUIDelegate;// 頁面前進、后退列表
@property (nonatomic, readonly, strong) WKBackForwardList *backForwardList;
// 默認構造器- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
// 已不再使用- (instancetype)initWithCoder:(NSCoder *)coder NS_UNAVAILABLE;
// 與UIWebView一樣的加載請求API- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;
// 加載URL- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL NS_AVAILABLE(10_11, 9_0);
// 直接加載HTML- (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
// 直接加載data- (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL NS_AVAILABLE(10_11, 9_0);
// 前進或者后退到某一頁面- (nullable WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item;
// 頁面的標題着撩,這昆支持KVO的
@property (nullable, nonatomic, readonly, copy) NSString *title;
// 當前請求的URL诅福,它是支持KVO的
@property (nullable, nonatomic, readonly, copy) NSURL *URL;
// 標識當前是否正在加載內容中,它是支持KVO的
@property (nonatomic, readonly, getter=isLoading) BOOL loading;
// 當前加載的進度拖叙,范圍為[0, 1]
@property (nonatomic, readonly) double estimatedProgress;
// 標識頁面中的所有資源是否通過安全加密連接來加載氓润,它是支持KVO的
@property (nonatomic, readonly) BOOL hasOnlySecureContent;
// 當前導航的證書鏈,支持KVO
@property (nonatomic, readonly, copy) NSArray *certificateChain NS_AVAILABLE(10_11, 9_0);
// 是否可以招待goback操作薯鳍,它是支持KVO的
@property (nonatomic, readonly) BOOL canGoBack;
// 是否可以執(zhí)行gofarward操作咖气,支持KVO
@property (nonatomic, readonly) BOOL canGoForward;
// 返回上一頁面,如果不能返回挖滤,則什么也不干
- (nullable WKNavigation *)goBack;
// 進入下一頁面崩溪,如果不能前進,則什么也不干
- (nullable WKNavigation *)goForward;
// 重新載入頁面
- (nullable WKNavigation *)reload;
// 重新從原始URL載入
- (nullable WKNavigation *)reloadFromOrigin;
// 停止加載數據
- (void)stopLoading;
// 執(zhí)行JS代碼
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ __nullable)(__nullable id, NSError * __nullable error))completionHandler;
// 標識是否支持左斩松、右swipe手勢是否可以前進伶唯、后退
@property (nonatomic) BOOL allowsBackForwardNavigationGestures;
// 自定義user agent,如果沒有則為nil
@property (nullable, nonatomic, copy) NSString *customUserAgent NS_AVAILABLE(10_11, 9_0);
// 在iOS上默認為NO惧盹,標識不允許鏈接預覽
@property (nonatomic) BOOL allowsLinkPreview NS_AVAILABLE(10_11, 9_0);
WKWebViewConfiguration 配置
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKPreferences 偏好設置
// 設置偏好設置config.preferences = [[WKPreferences alloc] init];
// 默認為0
config.preferences.minimumFontSize = 10;
// 默認認為YES
config.preferences.javaScriptEnabled = YES;
// 在iOS上默認為NO乳幸,表示不能自動通過窗口打開config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
WKUserContentController內容交互控制器通過 JS 與 webview 內容交互,需要用到這個類
// 只讀屬性钧椰,所有添加的WKUserScript都在這里可以獲取到
@property (nonatomic, readonly, copy) NSArray*userScripts;
// 注入JS
- (void)addUserScript:(WKUserScript *)userScript;
// 移除所有注入的JS
- (void)removeAllUserScripts;
// 添加scriptMessageHandler到所有的frames中粹断,則都可以通過
// window.webkit.messageHandlers..postMessage()
// 發(fā)送消息
// 比如,JS要調用我們原生的方法嫡霞,就可以通過這種方式了
- (void)addScriptMessageHandler:(id)scriptMessageHandler name:(NSString *)name;
// 根據name移除所注入的scriptMessageHandler
- (void)removeScriptMessageHandlerForName:(NSString *)name;
WKUserScript所注入的 JS 是 WKUserScript 對象
// JS源代碼
@property (nonatomic, readonly, copy) NSString *source;
// JS注入時間
@property (nonatomic, readonly) WKUserScriptInjectionTime injectionTime;
// 只讀屬性瓶埋,表示JS是否應該注入到所有的frames中還是只有main frame.
@property (nonatomic, readonly, getter=isForMainFrameOnly) BOOL forMainFrameOnly;
// 初始化方法,用于創(chuàng)建WKUserScript對象
// source:JS源代碼
// injectionTime:JS注入的時間
// forMainFrameOnly:是否只注入main frame
- (instancetype)initWithSource:(NSString *)source injectionTime:(WKUserScriptInjectionTime)injectionTime forMainFrameOnly:(BOOL)forMainFrameOnly;
WKUserScriptInjectionTime它是一個枚舉類型秒际,只有在文檔開始加載時注入和加載結束時注入悬赏。WKWebsiteDataStore存儲的Web內容iOS9.0以后才能使用這個類。它是代表webview不同的數據類型娄徊,包括cookies闽颇、disk、memory caches寄锐、WebSQL兵多、IndexedDB數據庫和本地存儲尖啡。
?// 默認數據存儲
+ (WKWebsiteDataStore *)defaultDataStore;
// 返回非持久化存儲,數據不會寫入文件系統
+ (WKWebsiteDataStore *)nonPersistentDataStore;
// 已經不可用- (instancetype)init NS_UNAVAILABLE;
// 只讀屬性剩膘,表示是否是持久化存儲
@property (nonatomic, readonly, getter=isPersistent) BOOL persistent;
// 獲取所有web內容的數據存儲類型集衅斩,比如cookies、disk等
+ (NSSet*)allWebsiteDataTypes;
// 獲取某些指定數據存儲類型的數據
- (void)fetchDataRecordsOfTypes:(NSSet*)dataTypes completionHandler:(void (^)(NSArray*))completionHandler;
// 刪除某些指定類型的數據
- (void)removeDataOfTypes:(NSSet*)dataTypes forDataRecords:(NSArray*)dataRecords completionHandler:(void (^)(void))completionHandler;
// 刪除某些指定類型的數據且修改日期是指定的日期
- (void)removeDataOfTypes:(NSSet*)websiteDataTypes modifiedSince:(NSDate *)date completionHandler:(void (^)(void))completionHandler;
WKWebsiteDataRecordiOS9.0以后才可用website 的數據存儲記錄類型
// 通常是域名@property (nonatomic, readonly, copy) NSString *displayName;
// 存儲的數據類型集@property (nonatomic, readonly, copy) NSSet*dataTypes;
WKSelectionGranularity選擇粒度表示在 webview 上選擇內容的粒度
typedef NS_ENUM(NSInteger, WKSelectionGranularity) {? ? WKSelectionGranularityDynamic,? ? WKSelectionGranularityCharacter,} NS_ENUM_AVAILABLE_IOS(8_0);
它是用于webview內容交互時選擇內容的粒度類型設置怠褐。比如說畏梆,當使用WKSelectionGranularityDynamic時,而所選擇的內容是單個塊奈懒,這時候granularity可能會是單個字符奠涌;當所選擇的web內容不限制于某個塊時,granularity可能會是單個塊磷杏。WKNavigationDelegate
@protocol WKNavigationDelegate@optional
// 決定導航的動作溜畅,通常用于處理跨域的鏈接能否導航。WebKit對跨域進行了安全檢查限制极祸,不允許跨域慈格,因此我們要對不能跨域的鏈接
// 單獨處理。但是遥金,對于Safari是允許跨域的浴捆,不用這么處理。
// 這個是決定是否Request
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
// 決定是否接收響應
// 這個是決定是否接收response
// 要獲取response汰规,通過WKNavigationResponse對象獲取
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
// 當main frame的導航開始請求時汤功,會調用此方法
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
;// 當main frame接收到服務重定向時,會回調此方法
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
// 當main frame開始加載數據失敗時溜哮,會回調
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
// 當main frame的web內容開始到達時,會回調
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation;
// 當main frame導航完成時色解,會回調
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;
// 當main frame最后下載數據失敗時茂嗓,會回調
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
// 這與用于授權驗證的API,與AFN科阎、UIWebView的授權驗證API是一樣的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler;
// 當web content處理完成時述吸,會回調
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0);@end
WKNavigationActionPolicy導航動作決定策略
typedef NS_ENUM(NSInteger, WKNavigationActionPolicy) {? ? WKNavigationActionPolicyCancel,
//不允許導航? ? WKNavigationActionPolicyAllow,} NS_ENUM_AVAILABLE(10_10, 8_0);
WKNavigationResponse導航響應類,可以獲取相關響應的信息NS_CLASS_AVAILABLE(10_10, 8_0)
@interface WKNavigationResponse : NSObject
// 是否是main frame
@property (nonatomic, readonly, getter=isForMainFrame) BOOL forMainFrame;
// 獲取響應response
@property (nonatomic, readonly, copy) NSURLResponse *response;
// 是否顯示MIMEType
@property (nonatomic, readonly) BOOL canShowMIMEType;
@end
WKNavigationActionWKNavigationAction對象包含關于導航的action的信息锣笨,用于make policy decisions
// 正在請求的導航的frame
@property (nonatomic, readonly, copy) WKFrameInfo *sourceFrame;
// 目標frame蝌矛,如果這是新的window,它會是nil
@property (nullable, nonatomic, readonly, copy) WKFrameInfo *targetFrame;
// 導航類型错英,如下面的小標題WKNavigationType
@property (nonatomic, readonly) WKNavigationType navigationType;
// 導航的請求@property (nonatomic, readonly, copy) NSURLRequest *request;
WKNavigationType枚舉類型
typedef NS_ENUM(NSInteger, WKNavigationType) {
// 鏈接已經點擊? ? WKNavigationTypeLinkActivated,? ??
// 表單提交? ? WKNavigationTypeFormSubmitted,? ??
// 前進入撒、后退? ? WKNavigationTypeBackForward,? ??
// 重新載入? ? WKNavigationTypeReload,? ??
// 表單重新提交? ? WKNavigationTypeFormResubmitted,? ??
// 其它? ? WKNavigationTypeOther = -1,} NS_ENUM_AVAILABLE(10_10, 8_0);
WKUIDelegate
@protocol WKUIDelegate
@optiona
l// 創(chuàng)建新的webview
// 可以指定配置對象、導航動作對象椭岩、window特性
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
// webview關閉時回調
- (void)webViewDidClose:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0);
// 調用JS的alert()方法
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
// 調用JS的confirm()方法
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
// 調用JS的prompt()方法
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
@end
WKBackForwardListWKBackForwardList表示webview中可以前進或者后退的頁面列表
NS_CLASS_AVAILABLE(10_10, 8_0)
@interface WKBackForwardList : NSObject
// 當前正在顯示的item(頁面)
@property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *currentItem;
// 后一頁茅逮,如果沒有就是nil
@property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *backItem;
// 前一頁璃赡,如果沒有就是nil
@property (nullable, nonatomic, readonly, strong) WKBackForwardListItem *forwardItem;
// 根據下標獲取某一個頁面的item
- (nullable WKBackForwardListItem *)itemAtIndex:(NSInteger)index;
// 可以進行goback操作的頁面列表
@property (nonatomic, readonly, copy) NSArray*backList;
// 可以進行goforward操作的頁面列表
@property (nonatomic, readonly, copy) NSArray *forwardList;
@end
```
WKBackForwardListItem
頁面導航前進、后退列表項
```
@interface WKBackForwardListItem : NSObject
// 該頁面的URL
@property (readonly, copy) NSURL *URL;
// 該頁面的title
@property (nullable, readonly, copy) NSString *title;
// 初始請求該item的請求的URL
@property (readonly, copy) NSURL *initialURL;
@end
```