WKWebView与JS交互
程序员文章站
2024-03-01 08:43:46
...
WKWebView与js交互有两种方式(url截取、消息回调)
方式一(截取)
//js发消息给oc(loadURL的方式)
function test2(){
loadURL("jiege://test2?name=js通过url给oc发消息");
}
function loadURL(url) {
var iFrame;
iFrame = document.createElement("iframe");
iFrame.setAttribute("src", url);
iFrame.setAttribute("style", "display:none;");
iFrame.setAttribute("height", "0px");
iFrame.setAttribute("width", "0px");
iFrame.setAttribute("frameborder", "0");
document.body.appendChild(iFrame);
// 发起请求后这个 iFrame 就没用了,所以把它从 dom 上移除掉
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
//oc接收js消息(拦截url)
/// 是否允许加载网页 在发送请求之前,通过拦截url决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSURL * urlString = [navigationAction.request URL];
//通过拦截urlString做交互
if ([[urlString scheme] isEqualToString:@"test"]) {
[_webModel jsCallObjectCTarget:self methodString:[urlString host] query:[urlString query]];
decisionHandler(WKNavigationActionPolicyCancel);
}
decisionHandler(WKNavigationActionPolicyAllow);
}
方式二 (回调)
oc接收js回调接收消息,首先在oc端注册回调,然后js发送消息
//oc注册通知
WKUserContentController *contentCon = [[WKUserContentController alloc]init];
[contentCon addScriptMessageHandler:self name:@"test"];
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
configuration.userContentController = contentCon;
_wkWebView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:configuration];
_wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate = self;
_wkWebView.allowsBackForwardNavigationGestures = YES;
[self.view addSubview:_wkWebView];
[_wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
//js发出通知
function test()
{
var message = {'test' :'You choose the A'};
window.webkit.messageHandlers.myName.postMessage(message);
}
//oc接收通知
//添加的js方法的回调
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSDictionary * messageDic = [[NSDictionary alloc]initWithDictionary:message.body];
NSString *test = messageDic[@"test"];
}
oc发消息给js
//注意:js不带参数方法后面加() 带参数加(json)
[_wkWebView evaluateJavaScript:[NSString stringWithFormat:@"%@()",testCallBack] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",response);
}];
//如果调取js的alert弹窗WKWebView需要实现以下代理:
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
// DLOG(@"msg = %@ frmae = %@",message,frame);
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}])];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.text = defaultText;
}];
[alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(alertController.textFields[0].text?:@"");
}])];
[self presentViewController:alertController animated:YES completion:nil];
}