WKWebView of OC and JS Interaction under ios

  • 2021-11-24 03:05:15
  • OfStack

In the last article, we used JavaScriptCore framework to rewrite the previous example. iOS8 Apple preferred HTML5, reconstructed UIWebVIew, and brought us WKWebView, which greatly improved its performance, stability and functions, and better supported the new features of HTML5. In this article, we will take WKWebView as a small test

1. WKWebView Framework

WKWebView's 14 classes and 3 protocols:

WKBackForwardList: A list of previously visited web pages, accessible through backward and forward actions.

WKBackForwardListItem: One page in the back list in webview.

WKFrameInfo: Contains layout information for 1 page.

WKNavigation: Contains loading progress information for 1 web page.

WKNavigationAction: Contains information that may cause changes to the navigation of a web page, and is used to determine whether a navigation change has been made.

WKNavigationResponse: Contains returned content information that may change the navigation of the web page, which is used to determine whether to make navigation changes.

WKPreferences: Summarizes the preferences of 1 webview.

WKProcessPool: Represents one web content load pool.

WKUserContentController: Provides a way to use JavaScript post information and inject script.

WKScriptMessage: Contains information emitted from the Web page.

WKUserScript: Represents a user script that can be accepted by a Web page.

WKWebViewConfiguration: Initializes the settings for webview.

WKWindowFeatures: Specifies window properties when a new Web page is loaded.

WKWebsiteDataStore: Includes Web page data storage and lookup.

WKNavigationDelegate: Provides a method for tracking the main window page loading process and determining whether the main window and child windows are loading new pages.

WKUIDelegate: Provides method callbacks to display Web pages with native controls.

WKScriptMessageHandler: Provides a callback method for receiving messages from a Web page.

2. Three proxy methods in WKWebView

1. WKNavigationDelegate

The agent provides methods that can be used to track the loading process (page load starts, load completes, load fails) and decide whether to perform jumps.


//  Called when the page starts loading 

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;

//  Called when content begins to return 

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

//  Called after the page has finished loading 

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;

//  Called when the page load fails 

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation; 

There are three proxy methods for page jump, which are divided into (receiving jump and deciding whether to jump or not)


//  Called after receiving a server jump request 

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;

//  After receiving the response, decide whether to jump 

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

//  Decide whether to jump before sending the request 

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

2. WKUIDelegate

Create a new WKWebView


//  Create 1 A new one WebView

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures; 

The remaining three proxy methods are all related to the pop-up prompt boxes in the interface, and the three prompt boxes (warning box, confirmation box and input box) in the web interface correspond to the three proxy methods respectively.


//  The interface pops up a warning box 

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

//  Confirmation box pops up on the interface 

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;

//  Interface pop-up input box 

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler; 

3. WKScriptMessageHandler

This protocol contains a method that must be implemented. This method is the key to the interaction between native and web. It can directly convert the received JS script into OC or Swift object.


//  From web Received in the interface 1 Called when a script is called 

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

3. Use WKWebView to override

Here we and the previous interface to do 1 point changes, before OC call JS when the bullet box processing, here I write, very depressed, method can be called in the past, but only alert method call js no effect, so here the output to the form of div, and added a button clear

nib files are not supported by WKWebView, so you need to initialize and load WebView with code here


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

config.preferences.minimumFontSize = 18;

 

self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];

[self.view addSubview:self.wkWebView];

 

 

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];

NSURL *baseURL = [[NSBundle mainBundle] bundleURL];

[self.wkWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL]; 

OC End:


//1. JS Call OC  Add processing scripts 

[userCC addScriptMessageHandler:self name:@"showMobile"];

[userCC addScriptMessageHandler:self name:@"showName"];

[userCC addScriptMessageHandler:self name:@"showSendMsg"];

 

//  Handle the corresponding event in the proxy method 

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

  NSLog(@"%@",NSStringFromSelector(_cmd));

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

 

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

    [self showMsg:@" I'm Little Red down there   The cell phone number is :18870707070"];

  }

   

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

    NSString *info = [NSString stringWithFormat:@" How do you do  %@,  Nice to meet you ",message.body];

    [self showMsg:info];

  }

   

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

    NSArray *array = message.body;

    NSString *info = [NSString stringWithFormat:@" This is my mobile phone number : %@, %@ !!",array.firstObject,array.lastObject];

    [self showMsg:info];

  }

}

 

// 2. native Call js

- (IBAction)btnClick:(UIButton *)sender {

  if (!self.wkWebView.loading) {

    if (sender.tag == 123) {

      [self.wkWebView evaluateJavaScript:@"alertMobile()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {

        //TODO

        NSLog(@"%@ %@",response,error);

      }];

    }

     

    if (sender.tag == 234) {

      [self.wkWebView evaluateJavaScript:@"alertName(' Xiao Hong ')" completionHandler:nil];

    }

     

    if (sender.tag == 345) {

      [self.wkWebView evaluateJavaScript:@"alertSendMsg('18870707070',' Climbing mountains on weekends is really a pleasure ')" completionHandler:nil];

    }

 

  } else {

    NSLog(@"the view is currently loading content");

  }

} 

JS end:


function clear() {

  document.getElementById('mobile').innerHTML = ''

  document.getElementById('name').innerHTML = ''

  document.getElementById('msg').innerHTML = ''

}

 

//OC Call JS Method list of 

function alertMobile() {

  // It has been called here   But I don't know why alert Method is not responding 

  //alert(' I'm the little yellow up there   The cell phone number is :13300001111')

  document.getElementById('mobile').innerHTML = ' I'm the little yellow up there   The cell phone number is :13300001111'

}

 

function alertName(msg) {

  //alert(' How do you do  ' + msg + ',  Nice to meet you, too ')

  document.getElementById('name').innerHTML = ' How do you do  ' + msg + ',  Nice to meet you, too '

}

 

function alertSendMsg(num,msg) {

  //window.alert(' This is my mobile phone number :' + num + ',' + msg + '!!')

  document.getElementById('msg').innerHTML = ' This is my mobile phone number :' + num + ',' + msg + '!!'

}

 

//JS Response method list 

function btnClick1() {

  window.webkit.messageHandlers.showMobile.postMessage(null)

}

 

function btnClick2() {

  window.webkit.messageHandlers.showName.postMessage('xiao Yellow ')

}

 

function btnClick3() {

  window.webkit.messageHandlers.showSendMsg.postMessage(['13300001111', 'Go Climbing This Weekend !!!'])

} 

4. Postscript

At this point, the whole series of examples have been completed, and the goods received in the process are quite abundant. Each article will summarize the knowledge points, and at the end of the article, show the address of the example DEMO.

Example DEMO: OC-JS-WKWebView_jb51. rar


Related articles: