WKWebView與JS的交互

用普通的UIWebView和JS交互 大概核心代碼是這樣的

- (void)setupWebView{
  self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
  self.webView.delegate = self;
  NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
  NSURL* url = [NSURL fileURLWithPath:path];
  NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
  [self.webView loadRequest:request];
  [self.view addSubview:self.webView];
}

代理方法

- (void)webViewDidFinishLoad:(UIWebView *)webView {
   //獲取js上下文
   self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];  
   //注入JS對(duì)象名稱 "JSObjec"
   self.jsContext[@"JSObjec"] = self;
   self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"異常信息:%@", exceptionValue);
    };
}

想調(diào)用的OC方法

- (void)getCall:(NSString *)callString{
   NSLog(@"Get----:%@", callString);
   //此處填寫(xiě)相應(yīng)的邏輯代碼
}

然后JS代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="margin-top: 20px">
<h2>JS與OC交互</h2>
<input type="button" value="喚起本地方法(call)" onclick="JSObjec.call()">
</div>
<script>
     
var call = function()
{
    var callInfo = JSON.stringify("www.itdecent.cn");//此處參數(shù)可自定義
        JSObjec.getCall(callInfo);
}
</script>
</body>
</html>

接下來(lái)是WKWebView的核心代碼

需要導(dǎo)入頭文件 代理

#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
@interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic,strong) WKWebView *webView;
- (void)setupWKWebView{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 設(shè)置偏好設(shè)置
    config.preferences = [[WKPreferences alloc] init];
    // 默認(rèn)為0
    config.preferences.minimumFontSize = 10;
    // 默認(rèn)認(rèn)為YES
    config.preferences.javaScriptEnabled = YES;
    // 在iOS上默認(rèn)為NO,表示不能自動(dòng)通過(guò)窗口打開(kāi)
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    config.processPool = [[WKProcessPool alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];
    //注意在這里注入JS對(duì)象名稱 "JSObjec"
    [config.userContentController addScriptMessageHandler:self name:@"JSObjec"];

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];

    NSURL *path = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:path]];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@",message.body);//message.body這里面內(nèi)容是js里傳過(guò)來(lái)的參數(shù)
//message.name這個(gè)是注入的JS對(duì)象名稱 "JSObjec" 
    if ([message.name isEqualToString:@"JSObjec"]) {
        // 打印所傳過(guò)來(lái)的參數(shù),只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull類型
        // 此處填寫(xiě)相應(yīng)的邏輯代碼
    }
}

然后JS代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="margin-top: 20px">
<h2>JS與OC交互</h2>
<input type="button" value="喚起本地方法(call)" onclick="JSObjec.call()">
</div>
<script>
     
var call = function()
{
    var callInfo = JSON.stringify("www.itdecent.cn");//此處參數(shù)可自定義
  //這里的內(nèi)容差不多全部一樣 只是調(diào)用的方法有區(qū)別 一定要注意區(qū)分
  //這個(gè)是用UIWebView時(shí)調(diào)用的方法 JSObjec.getCall(callInfo);
  //下面是用WKWebView調(diào)用的方法
    window.webkit.messageHandlers.JSObjec.postMessage(callInfo);
}
</script>
</body>
</html>

好了 希望這篇總結(jié)能幫助到大家。

后續(xù)補(bǔ)充

//從OC中獲取到一些數(shù)據(jù)后存入JS
NSString *sendToken = [NSString stringWithFormat:@"localStorage.setItem(\"accessToken\",'%@');",SecurityToken];

//WKUserScriptInjectionTimeAtDocumentStart JS加載前執(zhí)行
//WKUserScriptInjectionTimeAtDocumentEnd JS加載后執(zhí)行
//injectionTime配置不要寫(xiě)錯(cuò)  forMainFrameOnly  NO(全局窗口) YES(只限主窗口)
WKUserScript *sendTokenScript = [[WKUserScript alloc]initWithSource:sendToken injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];

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

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

  • 自從iOS8之后蘋果開(kāi)始建議替換掉笨重的UIWebView,WKWebView 自從iOS9.0以后,更趨于完善...
    sttech閱讀 833評(píng)論 2 2
  • 之前用UIWebView的時(shí)候,非常的爽,用JSContext這個(gè)類就可以做想做的事,現(xiàn)在要改成WKWebView...
    AgoniNemo閱讀 11,331評(píng)論 30 12
  • 前言 關(guān)于UIWebView的介紹,相信看過(guò)上文的小伙伴們,已經(jīng)大概清楚了吧,如果有問(wèn)題,歡迎提問(wèn)。 本文是本系列...
    Dark_Angel閱讀 29,515評(píng)論 67 291
  • 前言 關(guān)于UIWebView的介紹,相信看過(guò)上文的小伙伴們,已經(jīng)大概清楚了吧,如果有問(wèn)題,歡迎提問(wèn)。 本文是本系列...
    CoderLF閱讀 9,365評(píng)論 2 12
  • 前言 iOS開(kāi)發(fā)中,用來(lái)顯示一個(gè)html頁(yè)、H5頁(yè),經(jīng)常會(huì)用的一個(gè)控件是WebView。說(shuō)到WebView,你知道...
    Dark_Angel閱讀 23,742評(píng)論 31 287

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