WKWebViewJavascriptBridge

1.初始化一個(gè)WKWebview(viewdidload)

CGRect frame = self.view.frame;
    frame.size.height -= 64;
    WKWebViewConfiguration  *congif = [WKWebViewConfiguration new];
    congif.preferences.javaScriptEnabled = YES;
    congif.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    
    WKWebView *WebView = [[WKWebView alloc]initWithFrame:frame configuration:congif];
    WebView.navigationDelegate = self;
    WebView.UIDelegate = self;
    
    [self.view addSubview:WebView];
    self.webView = WebView;
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

2. 將此WKWebview與WKWebViewJavascriptBridge關(guān)聯(lián)(viewdidload)

if (_bridge) {
        return;
    }
    
    //[WKWebViewJavascriptBridge enableLogging];
    
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:WebView];
    
    [_bridge setWebViewDelegate:self];

3. js調(diào)oc方法(可以通過data給oc方法傳值,使用responseCallback將值再返回給js)

[_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
    }];

網(wǎng)頁有觸發(fā)事件后,才會(huì)調(diào)用括號(hào)里的方法。
這里注意testObjcCallback這個(gè)方法的標(biāo)示。html那邊的命名要跟ios這邊相同,才能調(diào)到這個(gè)方法。當(dāng)然這個(gè)名字可以兩邊商量著自定義。簡(jiǎn)單明確即可。

4.oc調(diào)js方法(通過data可以傳值,通過 response可以接受js那邊的返回值 )

id data = @{ @"greetingFromObjC": @"Hi there, JS!" };
    [_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
        NSLog(@"testJavascriptHandler responded: %@", response);
    }];

注意這里的 testJavascriptHandler也是個(gè)方法標(biāo)示。

5.oc給js傳值(通過 response接受返回值 )

[_bridge send:@"A string sent from ObjC to JS" responseCallback:^(id response) {
        NSLog(@"sendMessage got response: %@", response);
    }];

6.oc給js傳值(無返回值)

[_bridge send:@"A string sent from ObjC after Webview has loaded."];
最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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