27期_iOS_浅谈JS Bridge
2023-08-28 本文已影响0人
萧修
JS Bridge是桥接JS和Native的桥梁,分为JS调用Native和Native主动调用JS两种形式
URL Scheme:
通过浏览器的形式能打开app,在Xcode中配置
JS调原生
WKUserContentController
- addScriptMessageHandler
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userCC = configuration.userContentController;
// 注入对象
[userCC addScriptMessageHandler:self name:@"nativeObj"];
- removeScriptMessageHandler
// 清除对象
[userCC removeScriptMessageHandler:self name:@"nativeObj"];
- didReceiveScriptMessage
//处理前端调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
// 获取前端传来的参数
NSDictionary *msgBody = message.body;
// 如果是 nativeObj 就进行相应处理
if (![message.name isEqualToString:@"nativeObj"]) {
//
return;
}
}
- messageHandlers
//H5调用
window.webkit.messageHandlers.nativeObj.postMessage(data);
原生调JS
- evaluateJavaScript
一般发生于界面完成后调用,用来调用JS的函数并获取返回值风采方便
[self.webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
// 获取返回值 response
}];
- WKUserScript
可以控制注入时机,其中参数injecttionTime
设置为WKUserScriptInjectionTimeAtDocumentEnd
为网页加载完成时注
WKUserScript *wkcookieScript = [[WKUserScript alloc] initWithSource:self.javaScriptString
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[webView.configuration.userContentController addUserScript:wkcookieScript];