iOS原生與JS互調


1、使用 JSContext ,首先獲取當前webview JS上下文

JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; 

2.JS調用原生方法 

 __weak typeof(self) weakSelf = self;
    context[@"nativeTitle"] = ^(NSString *navTitle) {
        LRHLog(@"nativeTitle :%@",navTitle);
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf.webViewController setNaviTitle:navTitle];
            //統計web停留時間
            [strongSelf mobClickWebLoadingTimeWith:navTitle];
        });
    };

block中用來接收js的傳值,“nativeTitle” 為定義好的方法名

這里要注意兩個問題:第一、block中注意jsContext對象的循環引用; 第二、block中是在子線程,因此執行UI操作時,需要回到主線程。

3.原生調用JS

 [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"jsHandleNativeResult(/%@/)",jsStr]];

“jsHandleNativeResult” 為定義好的方法名

把js需要的參數進行拼接,通過定義好的方法傳給js。 


免責聲明!

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



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