ios WKWebView和JS交互注意細(xì)節(jié)

1.簽訂代理<WKScriptMessageHandler>

2.注冊交互方法名

WKUserContentController *userContentController = [[WKUserContentController ? ? ? ? ?alloc] init];

[userContentController addScriptMessageHandler:self.wsDelegate name:@"functionName"];

注:functionName:為JS和WKWebView交互時(shí)的比對信息,好比秘鑰,一定要一樣;self.wsDelegate:需創(chuàng)建一個(gè)弱引用的代理對象,不能直接引用self,否則導(dǎo)致控制器無法被釋放。

JS的調(diào)用方式:

window.webkit.messageHandlers.<name>.postMessage(<messageBody>)(<messageBody>為鍵值對組)

例如:window.webkit.messageHandlers.functionName.postMessage({key1: value1,key2:value2});(可以不傳參)

3.實(shí)現(xiàn)對應(yīng)交互方法的執(zhí)行內(nèi)容,需執(zhí)行代理方法

- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message

{

? ? ? ?if([message.name isEqualToString:@"functionName"])?

{

?NSLog(@"%@,%@",message.name,message.body);//執(zhí)行這個(gè)交互方法底下所需的操作

? ? }

}

4.創(chuàng)建一個(gè)弱引用的代理對象

? ? ? a.創(chuàng)建一個(gè)繼承于NSObject的類

? ? ? b.在.h文件中簽訂代理<WKScriptMessageHandler>,并創(chuàng)建代理對象和初始化方法

@property (nonatomic, weak) id<WKScriptMessageHandler> delegate;

- (instancetype)initWithDelegate:(id)delegate;

? ? ? ?c.在.m文件中實(shí)現(xiàn)初始化方法并實(shí)現(xiàn)代理方法

- (instancetype)initWithDelegate:(id)delegate

{

? ? self= [superinit];

? ? if(self)

? ? {

? ? ? ? _delegate= delegate;

? ? }

? ? return self;

}

#pragma mark ---------------實(shí)現(xiàn)代理方法---------------

- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message

{

? ? [self.delegate userContentController:userContentController didReceiveScriptMessage:message];

}

? ? ? ?d.在控制器中初始化一個(gè)對象,即第2點(diǎn)中的self.wsDelegate,以解決控制器無法釋放問題

5.移除注冊的交互方法

-(void)dealloc

{

? ? [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"functionName"];

}

6.若當(dāng)web調(diào)起alert時(shí),app進(jìn)行彈窗,需簽訂代理<WKUIDelegate>,同時(shí)執(zhí)行以下代理方法

#pragma mark - WKUIDelegate(js彈框需要實(shí)現(xiàn)的代理方法)

//使用了WKWebView后,在JS端調(diào)用alert()是不會(huì)在HTML中顯式彈出窗口,是我們需要在該方法中手動(dòng)彈出iOS系統(tǒng)的alert的

//該方法中的message參數(shù)就是我們JS代碼中alert函數(shù)里面的參數(shù)內(nèi)容

- (void)webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(void))completionHandler

{

? ? //? ? NSLog(@"js彈框了");

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容