WKWebView與js交互


1.WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler

2.

  // 創建一個webiview的配置項

       WKWebViewConfiguration *configuretion = [[WKWebViewConfiguration alloc] init];

        // Webview的偏好設置

        //.WKPreferences()

        // 設置偏好設置

        configuretion.preferences = [[WKPreferences alloc]init];

        configuretion.preferences.minimumFontSize = 10;

        configuretion.preferences.javaScriptEnabled = true;

        configuretion.processPool = [[WKProcessPool alloc]init];

        // 通過jswebview內容交互配置

        configuretion.userContentController = [[WKUserContentController alloc] init];

        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        //OC注冊供JS調用的方法

        [ configuretion.userContentController addScriptMessageHandler:self name:@"WKOcOrAndroidModel"];

        // 默認是不能通過JS自動打開窗口的,必須通過用戶交互才能打開

        configuretion.preferences.javaScriptCanOpenWindowsAutomatically = NO;

        _wkwebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuretion];//self.view.bounds

        [_wkwebView goBack];

        [_wkwebView goForward];

        _wkwebView.navigationDelegate = self;

        _wkwebView.UIDelegate = self;

        NSURL *url = [NSURL URLWithString:urlStr];  //測試本地H5

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        [_wkwebView loadRequest:request];

3.

/*

 *開始加載WKWebView時調用的方法

 */

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { // 類似UIWebView -webViewDidStartLoad:

    NSLog(@"didStartProvisionalNavigation");

    [self.view showLoading];

}

 

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {

    NSLog(@"didCommitNavigation");

}

/*

 *結束加載WKWebView時調用的方法

 */

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // 類似 UIWebView webViewDidFinishLoad:

    NSLog(@"+++++++didFinishNavigation");

    [self.view hideLoading];

    

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        dispatch_async(dispatch_get_main_queue(), ^{

            if (_wkwebView.title.length > 0) {

                self.title = _wkwebView.title;

            }

        });

    });

 

}

/*

 *加載WKWebView失敗時調用的方法

 */

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {

    // 類似 UIWebView - webView:didFailLoadWithError:

    

    NSLog(@"didFailProvisionalNavigation");

     [self loadFailedUI:@"啊哦加載失敗!"];

    

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {

    NSLog(@"decidePolicyForNavigationResponse");

//    decisionHandler(WKNavigationActionPolicyAllow);

    decisionHandler(WKNavigationResponsePolicyAllow);

}

 

 

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    decisionHandler(WKNavigationActionPolicyAllow);

    // 類似 UIWebView -webView: shouldStartLoadWithRequest: navigationType:

    

    NSLog(@"4.%@",navigationAction.request);

    

}

 

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController

      didReceiveScriptMessage:(WKScriptMessage *)message {

    if ([message.name isEqualToString:@"WKOcOrAndroidModel"]) {

        // 打印所傳過來的參數,只支持NSNumber, NSString, NSDate, NSArray,

        // NSDictionary, and NSNull類型

        NSLog(@"%@",message.body);

    }

}

4.js的alert彈出要調用

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

    NSLog(@"%s", __FUNCTION__);

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:message preferredStyle:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        completionHandler();

    }]];

    

    [self presentViewController:alert animated:YES completion:NULL];

    NSLog(@"%@", message);

}

5.

iOS 8 引入WKWebViewWKWebView 不支持JavaScriptCore的方式但提供message handler的方式為JavaScript 與Objective-C 通信.

Objective-C 中使用WKWebView的以下方法調用JavaScript:

- (void)evaluateJavaScript:(NSString *)javaScriptString

         completionHandler:(void (^)(id, NSError *))completionHandler

如果JavaScript 代碼出錯, 可以在completionHandler 進行處理.

Objective-C 中注冊 message handler:

// WKScriptMessageHandler protocol?

 

- (void)userContentController:(WKUserContentController *)userContentController

    didReceiveScriptMessage:(WKScriptMessage *)message

{

    NSLog(@"Message: %@", message.body);

}

 

[userContentController addScriptMessageHandler:handler name:@"myName"];

JavaScript 將信息發給Objective-C:

// window.webkit.messageHandlers.<name>.postMessage();?

 

function postMyMessage()? {?

    var message = { 'message' : 'Hello, World!', 'numbers' : [ 1, 2, 3 ] };?

    window.webkit.messageHandlers.myName.postMessage(message);?

}


免責聲明!

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



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