Preface: WKWebView
As UIWebView has been deprecated, it is recommended to use WKWebView with WKScriptMessageHandler for interactions between iOS and JS.
WKWebView is a class in Apple’s WebKit framework, introduced in iOS 8, responsible for rendering and displaying web pages. It is faster than UIWebView, uses less memory, and supports more HTML features.
JavaScript Calls iOS using WKWebView
Example: Clicking an image on the page triggers an iOS method to enlarge the image display.
1.1 JS Code in WKWebView:
Code language: javascriptCopy
window.webkit.messageHandlers.openImage.postMessage($(this).attr("src"));
1.2 iOS Side Code Using WKWebView
- Conform to the WKScriptMessageHandler protocol
Code language: javascriptCopy
@interface QCTWebViewController ()
- Implement the callback protocol for WKWebView receiving ScriptMessage
Code language: javascriptCopy
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ if ([message.name caseInsensitiveCompare:k_openImage4js] == NSOrderedSame) { NSLog(@"message.name:%@,message.body:%@",message.name,message.body); // [WKWebViewWKScriptMessageHandlerController showAlertWithTitle:message.name message:message.body cancelHandler:nil]; } }
1.2.1 Initialize WKWebView with a Configuration Object
Code language: javascriptCopy
//! Add ScriptMessageHandler to userContentController and specify name//WKUserContentController *userContentController = [[WKUserContentController alloc] init];//[userContentController addScriptMessageHandler:self name:@"openImage"];//! Configure configuration using userContentController with ScriptMessageHandlerWKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];//configuration.userContentController = userContentController;//! Initialize webView using configuration object_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
1.2.1 Listening to Messages in WKWebView
To avoid circular reference issues: perform add listener in -viewWillAppear: method, and remove listener in -viewWillDisappear: method.
Code language: javascriptCopy
NSString * const k_openImage4js = @"openImage";extern NSString * _Nonnull const k_openImage4js;- (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [_webView.configuration.userContentController removeScriptMessageHandlerForName:k_openImage4js]; }- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; //WKUserContentController *userContentController = [[WKUserContentController alloc] init]; [_webView.configuration.userContentController addScriptMessageHandler:self name:k_openImage4js]; }
- Enlarge Image
Code language: javascriptCopy
- (void)ImageZoomScaleWithUrl:(NSString*)url{ CRMImageZoomScaleViewController *detail = [[CRMImageZoomScaleViewController alloc]init]; // detail.maximumZoomScale = 4.8f; detail.imagePath = url; detail.type = @"yes"; __weak __typeof__(self) weakSelf = self; [UIView transitionWithView:self.navigationController.view duration:0.25 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ [weakSelf.navigationController pushViewController:detail animated:NO]; } completion:nil];}
II iOS Executes JS
Accomplished through WKWebView’s -evaluateJavaScript:completionHandler:
method
The -evaluateJavaScript:completionHandler: method of WKWebView can execute JS code. However, this method will only respond after the entire webView has finished loading.
2.1 Execute JS
- iOS uses WKWebView’s
evaluateJavaScript:completionHandler:
method to execute concatenated JS code;
Code language: javascriptCopy
[self.webView evaluateJavaScript:@"ocToJs('loginSucceed', 'tokenString')" completionHandler:^(id response, NSError *error) {}];
- js
Code language: javascriptCopy
//! iOS calls JS to display data box
//! Entry point for iOS to call JSfunction ocToJs(action, params) { document.getElementById("returnValue").innerHTML = action + '?' + params;}
2.2 Retrieve Webpage Title
- Retrieve webpage title: Execute only after load request is completed
//! This method is called each time WKWebView completes a load request
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
Code language: javascriptCopy
#if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT title = title.length>0 ? title: [_webView title];#else title = title.length>0 ? title: [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];#endif
III Load Local HTML Files
- loadHTMLString4WkWebView source code
Code language: javascriptCopy
#pragma mark - ******** Load Local HTML//NSString * const k_localHtml4csdn = @"csdn21.html";- (void)localHtmlClicked{ NSString *path = [[NSBundle mainBundle] pathForResource:k_localHtml4csdn ofType:nil]; NSString *htmlString = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; [_webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];}
IV Anti-Packet Sniffing
Anti-Packet Sniffing
Render proxy sniffing methods like Thor, Charles, and Burp ineffective.
Code language: javascriptCopy
configuration.connectionProxyDictionary = @{};
However, it cannot prevent tools like Wireshark which directly capture packets through the network card. If your request protocol is very important, be sure to sign or encrypt the request and try to avoid declaring AES encryption keys in plaintext. For details, see the iOS security specification guide on parameter signing: parameters are sorted according to ASCII code from small to large, concatenated, and encrypted (using a recursive implementation method) [Example: Barcode payment integrated front-end platform application for a refund]. | Accumulation plan from CSDN download demo address: https://download.csdn.net/download/u011018979/15483107 Rule: 1. The demo array is represented by [], and the object (dictionary) is represented by {} for sorting and concatenation. 2. Array sorting is optional. Within the array, only string elements are sorted, not participating with dictionary keys for sorting. Dictionary and array are sorted independently. Original text: https://blog.csdn.net/z929118967/article/details/115669856 Application Scenario: Prevent request parameters from being maliciously modified; for instance, when interfacing with third-party payments, the third party may require parameters to be sorted by ASCII code from small to large.
See Also
iOS interaction with JS using the JSExport protocol & interaction of android with JS
>
Large Image Browser
- ImageZoomScale: iOS uses UIScrollView to implement image zoom preview and supports reduction.
- iOS Large Image Browser (Application scenario: view large images of risk merchant proof materials supporting slide switching)
Download Demo source code from CSDN: https://download.csdn.net/download/u011018979/16039540
- Application Scenario: Viewing multiple large images, such as viewing proof materials of risky merchants, with image support for sliding switch
- Article: https://blog.csdn.net/z929118967/article/details/115077471
- Main Features: After entering the viewer, you can swipe left or right to view the next/previous image and support slide-down to exit viewer.
Principle of “Same Layer Rendering”
WeChat Mini Programs render using WKWebView on iOS. Internally, WKWebView uses a layered approach for rendering, which renders the Compositing Layer generated by the WebKit kernel into iOS’s WKCompositingView, a native client view. However, the kernel typically renders multiple DOM nodes onto a single Compositing Layer, so there’s no one-to-one mapping between the Compositing Layer and the DOM nodes. However, it’s found that when the CSS property of a DOM node is set to overflow: scroll (in earlier versions, you must also set -webkit-overflow-scrolling: touch), WKWebView generates a WKChildScrollView for it, which maps to the DOM node. This WKChildScrollView is a subclass of a native UIScrollView, meaning scrolling within the WebView is carried by a real native scrolling component. WKWebView does this to give the iOS WebView scrolling a smoother experience. Though WKChildScrollView is a native component, the WebKit kernel has already managed its layered relationship with other DOM nodes, so you can directly use WXSS to control the hierarchy without worrying about occlusions.
The “same layer rendering” on the iOS side of Mini Programs is also implemented through WKChildScrollView. Once the native component is attached, it’s directly mounted under the previously created WKChildScrollView container. The general process is as follows:
- Create a DOM node and set its CSS properties to overflow: scroll and -webkit-overflow-scrolling: touch;
- Notify the client to find the corresponding native WKChildScrollView component for that DOM node;
- Mount the native component onto the WKChildScrollView node as its child View.
>
Through the above process, the native component of the Mini Program is inserted into the WKChildScrollView, corresponding to the native ScrollView that was created in Step 1 of the DOM node. At this point, modifying the style attribute of this DOM node will also apply to the native component. Therefore, “same layer rendering” native components and ordinary built-in components do not differ in performance.
Same layer rendering not only solves the hierarchy issue of native components but also enriches the display and interaction capabilities of native components.
The table below lists the native components that already support “same layer rendering.” Other components (textarea, camera, webgl, and input) will be gradually launched in the near future. You can now try to optimize your Mini Program with “same layer rendering.”
Native Components Supporting Same Layer Rendering |
Minimum Version |
---|---|
video |
v2.4.0 |
map |
v2.7.0 |
canvas 2d (new interface) |
v2.9.0 |
live-player |
v2.9.1 |
live-pusher |
v2.9.1 |
Communication Relationship Among UIProcess, WebContent, NetworkProcess Three Major Processes
NetworkProcess:
Mainly responsible for network request loading; all pages share this process. Consistent with native network request development, the NetworkProcess also initiates and manages network requests through the encapsulated NSURLSession. However, this process involves more callbacks for network progress and various network protocol management, such as resource caching protocol, HSTS protocol, cookie management protocol, etc.
WebContent Process: Mainly responsible for managing page resources, including forward and back history, pageCache, and parsing and rendering of page resources. This process notifies UIProcess of events via delegation.
UIProcess: Primarily responsible for interacting with WebContent, sharing the same process as the APP. It configures WebView settings and receives various messages from the WebContent process, making decisions for task execution in collaboration with business code, like whether to initiate a request, and whether to accept a response, etc.