iOS WKWebView與JS交互

本篇主要給大家分享的是OC版的WKWebView與JS的交互.,Swift版本請(qǐng)查看Swift WKWebView與JS交互.

我還寫了另外一篇,綜合UIWebView與WKWebView與JS交互的文章.歡迎收藏.
iOS OC與JS交互(WebView監(jiān)聽事件)

在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)頁加載成功的時(shí)候,我們會(huì)調(diào)用一些JS代碼對(duì)網(wǎng)頁進(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)頁加載完成的時(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);
    }];
}

通過以上操作就成功獲取到input標(biāo)簽的value屬性值了.如果報(bào)錯(cuò),可以通過error進(jìn)行相應(yīng)的錯(cuò)誤處理.
其實(shí)也可以設(shè)置一些JS對(duì)網(wǎng)頁進(jìn)行一些設(shè)置.

下面附帶一點(diǎ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

注:通過name獲取的是個(gè)數(shù)組,可能有多個(gè),方法名Elements是個(gè)復(fù)數(shù),不要忘了寫s,我之前就被坑過.

二.運(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)頁加載完成時(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é)束寫上回調(diào).

completionHandler();

三.JS調(diào)用OC

當(dāng)JS端想傳一些數(shù)據(jù)給iOS.那它們會(huì)調(diào)用下方方法來發(fā)送.

window.webkit.messageHandlers.<方法名>.postMessage(<數(shù)據(jù)>)

上方代碼在JS端寫會(huì)報(bào)錯(cuò),導(dǎo)致網(wǎng)頁后面業(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傳來的數(shù)據(jù)了.但是控制器不走-dealloc方法.

四.JS調(diào)用OC 內(nèi)存泄露處理

關(guān)于內(nèi)存泄露問題.此處參考:使用WKWebView替換UIWebView
思路是另外創(chuàng)建一個(gè)代理對(duì)象,然后通過代理對(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)~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 前言 關(guān)于UIWebView的介紹,相信看過上文的小伙伴們,已經(jīng)大概清楚了吧,如果有問題,歡迎提問。 本文是本系列...
    Dark_Angel閱讀 29,033評(píng)論 67 291
  • 上一篇文章講解了WKWebView如何加載一個(gè)簡單的靜態(tài)html頁面。下面,講解如何如js端交互。 一.關(guān)于Mes...
    秦萍健閱讀 810評(píng)論 0 5
  • 一.WKWebView的特性 1.在性能、穩(wěn)定性、功能方面有很大提升(最直觀的體現(xiàn)就是加載網(wǎng)頁是占用的內(nèi)存,模擬器...
    秦萍健閱讀 450評(píng)論 0 4
  • 1.1 WKScriptMessageHandler協(xié)議 WKScriptMessageHandler其實(shí)就是一個(gè)...
    Kasign閱讀 7,226評(píng)論 0 11
  • 前言 關(guān)于UIWebView的介紹,相信看過上文的小伙伴們,已經(jīng)大概清楚了吧,如果有問題,歡迎提問。 本文是本系列...
    CoderLF閱讀 9,016評(píng)論 2 12