本篇主要給大家分享的是OC版的WKWebView與JS的交互.,Swift版本請(qǐng)查看Swift WKWebView與JS交互.
我還寫(xiě)了另外一篇,綜合UIWebView與WKWebView與JS交互的文章.歡迎收藏.
iOS OC與JS交互(WebView監(jiān)聽(tīng)事件)
在iOS 8以后,是不是有很多小伙伴把UIWebView轉(zhuǎn)為WKWebView,同樣的之前在UIWebView與JS通信的方法也需要換成WKWebView中的處理方式.那么下面我就分享一下WKWebView與JS的交互.
一. WKWebView調(diào)用JS
總之一行代碼搞定:
[webView evaluateJavaScript:@"我是JS" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
}];
首先使用WKWebView.你需要導(dǎo)入WebKit #import <WebKit/WebKit.h>
然后初始化一個(gè)WKWebView,設(shè)置WKNavigationDelegate
,并且執(zhí)行WKNavigationDelegate的方法.在網(wǎng)頁(yè)加載成功的時(shí)候,我們會(huì)調(diào)用一些JS代碼對(duì)網(wǎng)頁(yè)進(jìn)行設(shè)置.
WKWebView本身提供一個(gè)方法進(jìn)行處理JS代碼.
javaScriptString:
所執(zhí)行的JS代碼
completionHandler:
回調(diào)
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;
使用以上方法,在網(wǎng)頁(yè)加載完成的時(shí)候進(jìn)行操作.
例如我要獲取一個(gè)標(biāo)簽的內(nèi)容.標(biāo)簽如下.
<input style="display:none;" name="input" value='I am Input'/>
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//設(shè)置JS
NSString *inputValueJS = @"document.getElementsByName('input')[0].attributes['value'].value";
//執(zhí)行JS
[webView evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"value: %@ error: %@", response, error);
}];
}
通過(guò)以上操作就成功獲取到input標(biāo)簽的value屬性值了.如果報(bào)錯(cuò),可以通過(guò)error進(jìn)行相應(yīng)的錯(cuò)誤處理.
其實(shí)也可以設(shè)置一些JS對(duì)網(wǎng)頁(yè)進(jìn)行一些設(shè)置.
下面附帶一點(diǎn)簡(jiǎn)單的JS代碼.
//獲取標(biāo)簽內(nèi)容
document.getElementsByName('name')[0].value
document.getElementById('id').value
//獲取標(biāo)簽?zāi)硞€(gè)屬性
document.getElementsByName('name')[0].attributes['attribute'].value
document.getElementById('name').attributes['attribute'].value
注:通過(guò)name獲取的是個(gè)數(shù)組,可能有多個(gè),方法名Elements是個(gè)復(fù)數(shù),不要忘了寫(xiě)s,我之前就被坑過(guò).
二.運(yùn)行時(shí)加載JS代碼
使用此方法的時(shí)候,WKWebView的初始化方法就要使用如下方法,設(shè)置配置.
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
注入需要執(zhí)行的代碼.
NSString *js = @"I am JS Code";
//初始化WKUserScript對(duì)象
//WKUserScriptInjectionTimeAtDocumentEnd為網(wǎng)頁(yè)加載完成時(shí)注入
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//根據(jù)生成的WKUserScript對(duì)象,初始化WKWebViewConfiguration
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addUserScript:script];
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
[_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"URL"]]];
[self.view addSubview:_webView];
上邊假如有一些JS操作執(zhí)行,這個(gè)時(shí)候就觸發(fā)它的另一個(gè)代理WKUIDelegate
的回調(diào)方法.
//在JS端調(diào)用alert函數(shù)時(shí),會(huì)觸發(fā)此代理方法罢维。
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
//JS端調(diào)用confirm函數(shù)時(shí)谒养,會(huì)觸發(fā)此代理方法。
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
//JS端調(diào)用prompt函數(shù)時(shí)渗常,會(huì)觸發(fā)此代理方法。
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;
以上方法需要在方法的結(jié)束寫(xiě)上回調(diào).
completionHandler();
三.JS調(diào)用OC
當(dāng)JS端想傳一些數(shù)據(jù)給iOS.那它們會(huì)調(diào)用下方方法來(lái)發(fā)送.
window.webkit.messageHandlers.<方法名>.postMessage(<數(shù)據(jù)>)
上方代碼在JS端寫(xiě)會(huì)報(bào)錯(cuò),導(dǎo)致網(wǎng)頁(yè)后面業(yè)務(wù)不執(zhí)行.可使用
try-catch
執(zhí)行.
那么在OC中的處理方法如下.它是WKScriptMessageHandler的代理方法.name和上方JS中的方法名相對(duì)應(yīng).
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
具體如下:
//設(shè)置addScriptMessageHandler與name.并且設(shè)置<WKScriptMessageHandler>協(xié)議與協(xié)議方法
[[_webView configuration].userContentController addScriptMessageHandler:self name:@"方法名"];
//WKScriptMessageHandler協(xié)議方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
//code
}
到目前為止,已經(jīng)可以檢測(cè)到JS傳來(lái)的數(shù)據(jù)了.但是控制器不走-dealloc
方法.
四.JS調(diào)用OC 內(nèi)存泄露處理
關(guān)于內(nèi)存泄露問(wèn)題.此處參考:使用WKWebView替換UIWebView
思路是另外創(chuàng)建一個(gè)代理對(duì)象,然后通過(guò)代理對(duì)象回調(diào)指定的self.
@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>
@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
@end
@implementation WeakScriptMessageDelegate
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate
{
self = [super init];
if (self) {
_scriptDelegate = scriptDelegate;
}
return self;
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
[self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}
@end
使用時(shí),只需要將原本的self
修改為WeakScriptMessageDelegate
的一個(gè)實(shí)例就行了.
//設(shè)置addScriptMessageHandler與name.并且設(shè)置<WKScriptMessageHandler>協(xié)議與協(xié)議方法
[[_webView configuration].userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"方法名"];
最后我們創(chuàng)建的代理要在控制器的-dealloc
方法中銷毀.
- (void)dealloc {
...
[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"方法名"];
...
}
好了,以上就是我分享的內(nèi)容了.有什么不對(duì)的地方,或者不全面的地方還請(qǐng)各位大神指點(diǎn)~~