WKWebViewで下記のHTMLを開く。
ボタンを押すと、Native側のメソッドが呼ばれ、メッセージを受け取る。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
</head>
<body>
<button onclick="window.webkit.messageHandlers.test1.postMessage('こんにちは')">こんにちは</button>
<button onclick="window.webkit.messageHandlers.test2.postMessage('こんばんは')">こんばんは</button>
</body>
</html>
Native側の(Objective-Cによる)実装は下記のようになる。
@interface ViewController () <WKScriptMessageHandler>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
WKWebViewConfiguration* webViewConfiguration = [WKWebViewConfiguration new];
[webViewConfiguration.userContentController addScriptMessageHandler:self name:@"test1"];
[webViewConfiguration.userContentController addScriptMessageHandler:self name:@"test2"];
WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webViewConfiguration];
[self.view addSubview:webView];
[webView loadRequest:[[NSURLRequest alloc]initWithURL:[[NSURL alloc] initWithString:kURL]]];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"%@", message.name);
NSLog(@"%@", message.body);
}
@end
WKWebViewConfigurationのuserContentControllerのaddScriptMessageHandlerで、
メッセージを受け取るWKScriptMessageHandlerオブジェクトとメッセージハンドラーの名前と指定する。
たとえば、
[webViewConfiguration.userContentController addScriptMessageHandler:self name:@"test1"];
このコードでは、メッセージハンドラーの名前は”test1″を指定しているので、JavaScriptの
window.webkit.messageHandlers.test1.postMessage('こんにちは')
このコードが実行されたら、メッセージを受け取る。
JavaScript側の呼び出しは、
window.webkit.messageHandlers.メッセージハンドラー名.postMessage(送信するメッセージ)
となる。
メッセージを受け取ったらWKScriptMessageHandlerの
「- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;」
が呼ばれる。
どのメッセージハンドラーから、何のメッセージが送られたかは、WKScriptMessageオブジェクトのnameとbodyで取得できる。
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"%@", message.name);
NSLog(@"%@", message.body);
}