h5 调原生方法一点小问题

393 阅读1分钟

h5

toApp () {
            const type = this.IsIA()
            if (this.result) { // 签署成功方法
                if (type == 1) { // 安卓
                    window.android.signContractSuccessful()
                } else { // ios
                    window.webkit.messageHandlers.signContractSuccessful.postMessage()
                }
            } else { // 签署失败方法
                if (type == 1) { // 安卓
                    window.android.signContractFail()
                } else { // ios
                    window.webkit.messageHandlers.signContractFail.postMessage()
                }
            }
        },

这里  window.webkit.messageHandlers.signContractFail.postMessage() 应该改成window.webkit.messageHandlers.signContractFail.postMessage('')必带参数 webkit api规定

iOS

- (KGWebView *)webview {
    if (!_webview) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];

        [userContentController addScriptMessageHandler:self name:@"signContractSuccessful"];

        [userContentController addScriptMessageHandler:self name:@"signContractFail"];

        configuration.userContentController = userContentController;
        _webview = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
        _webview.UIDelegate = self;
        _webview.navigationDelegate = self;
    }

    return _webview;
}

#pragma mark - WKScriptMessageHandler -

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"signContractSuccessful"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KGSignContractResultNotification object:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    if ([message.name isEqualToString:@"signContractFail"]) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

 注意遵守一下代理 

WKScriptMessageHandler