客户端与内嵌H5之间可以通过以下几种方式进行通信:

1,841 阅读2分钟

客户端与内嵌H5之间可以通过以下几种方式进行通信:

  1. URL Scheme:客户端可以通过URL Scheme向内嵌H5发送消息,在H5中通过JavaScript识别URL Scheme并作出相应处理。
  2. JavaScript Bridge:客户端可以通过WebView提供的JavaScript Bridge,向内嵌H5注入JavaScript对象,H5可以通过该对象与客户端进行交互。
  3. postMessage:客户端可以通过WebView提供的postMessage方法,向内嵌H5发送消息,H5可以通过监听message事件来接收消息并作出相应处理。
  4. localStorage:客户端可以通过WebView提供的localStorage,将数据存储在本地,并在H5中读取这些数据,实现数据共享。
  5. Native API:客户端可以自己编写Native API,H5可以通过JavaScript调用这些API来与客户端进行通信。

以下是几种通信方式的代码示例:

  1. URL Scheme 客户端代码:
objcCopy code
NSURL *url = [NSURL URLWithString:@"myapp://message?type=hello"];
[[UIApplication sharedApplication] openURL:url];

H5代码:

javascriptCopy code
if (location.href.indexOf('type=hello') !== -1) {
  // 处理客户端发送的消息
}
  1. JavaScript Bridge 客户端代码:
objcCopy code
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
// 注入JavaScript对象
NSMutableDictionary *config = [NSMutableDictionary dictionary];
[config setObject:@"value" forKey:@"key"];
WKUserScript *script = [[WKUserScript alloc] initWithSource:[NSString stringWithFormat:@"window.nativeConfig=%@;", [config JSONString]] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[webView.configuration.userContentController addUserScript:script];
// 实现JavaScript回调
[webView.configuration.userContentController addScriptMessageHandler:self name:@"nativeCallback"];

H5代码:

javascriptCopy code
// 获取JavaScript对象
var nativeConfig = window.nativeConfig;
console.log(nativeConfig.key); // 输出"value"
// 调用JavaScript回调
window.webkit.messageHandlers.nativeCallback.postMessage('hello');
  1. postMessage 客户端代码:
objcCopy code
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
// 发送消息到H5
[webView evaluateJavaScript:@"window.postMessage('hello', '*');" completionHandler:nil];

H5代码:

javascriptCopy code
// 监听消息事件
window.addEventListener('message', function(event) {
  if (event.data === 'hello') {
    // 处理客户端发送的消息
  }
});
  1. localStorage 客户端代码:
objcCopy code
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
// 存储数据到localStorage
[webView evaluateJavaScript:@"localStorage.setItem('key', 'value');" completionHandler:nil];

H5代码:

javascriptCopy code
// 读取localStorage中的数据
var value = localStorage.getItem('key');
console.log(value); // 输出"value"
  1. Native API 客户端代码:
objcCopy code
// 定义Native API
- (void)showAlert:(NSString *)message {
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
  [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
  [self presentViewController:alertController animated:YES completion:nil];
}
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
// 注入Native API
WKUserContentController *userContentController = webView.configuration.userContentController;
[userContentController addScriptMessageHandler:self name:@"nativeAPI"];
[userContentController addUserScript:[[WKUserScript alloc] initWithSource:@"function showAlert(message) { window.webkit.messageHandlers.nativeAPI.postMessage({ action: 'showAlert', message: message }); }" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];

H5代码:

javascriptCopy code
// 调用Native API
window.webkit.messageHandlers.nativeAPI.postMessage({ action: 'showAlert', message: 'Hello' });

在客户端中实现WKScriptMessageHandler协议,以接收来自H5的消息:

objcCopy code
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  if ([message.name isEqualToString:@"nativeAPI"]) {
    NSDictionary *data = message.body;
    NSString *action = data[@"action"];
    if ([action isEqualToString:@"showAlert"]) {
      NSString *message = data[@"message"];
      [self showAlert:message];
    }
  }
}