iOS和Android的Webview:如何关闭Webview并返回到应用程序?

4
我正在开发一个网页,将通过iOS和Android应用程序使用webview调用。
  1. 该网页将提示用户填写表格
  2. 用户必须填写字段并提交表单
  3. 一旦表单被提交,我会将用户重定向到另一个URL
  4. 当加载此最终URL时,我需要关闭webview
这是否可以在网页内完成,还是由打开webview的应用程序进行管理?如何可能实现?
我读过有关UIWebViewDelegate的内容,但不确定它是否是正确的解决方案。
谢谢
3个回答

5

在你的最终 URL 中使用哈希标记,例如http://domain.com/thanks.html#closeWebview,然后观察 URL。

在 Android 上:

mWebview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if (url.endsWith("#closeWebview")){
            mWebview.setVisibility(View.GONE);
        }
    }
});

2
你可以使用UIWebViewDelegate方法来跟踪页面是否已加载并执行任何操作:
-(void)webViewDidFinishLoad:(UIWebView *)webView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
-(void)webViewDidStartLoad:(UIWebView *)webView

例如:您可以使用didFinish方法,如下所示:
-(void)webViewDidFinishLoad:(UIWebView *)webView{
     if(finalURLReached)
         [self dismissViewControllerAnimated:YES completion:nil];
}

0

使用新的WKWebView解决方案(UIWebView已被弃用!):

  1. 通过WKNavigationDelegate监听导航事件

    webView.navigationDelegate = myNavigationDelegate // 或者在自己的WebView ViewController中实现时使用self

  2. 在此代理中监听特定的触发URL

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    print("request: (navigationAction.request.description)")

        if navigationAction.request.description.hasSuffix("/yourFinishUrlEnding") {            
            print("url matches...")
            decisionHandler(.allow)
            closeWebview()
        } else {
            decisionHandler(.allow)
        }
    }
    
  3. 关闭WebView(适用于所有呈现变体)

将以下代码添加到您分配的WKNavigationDelegate中:
func closeWebview() {
    if(controller.presentingViewController != nil && (nil == controller.navigationController || controller.navigationController?.viewControllers.count < 2 )){
        controller.dismiss(animated: true, completion: completion)
    }else{
        controller.navigationController?.delegate = nil;
        // self.animationInteractor.forceCompleteAnimation(.Left)
        let c = controller.navigationController?.viewControllers.count
        let ct = c! - 2;
        controller.navigationController?.popViewController(animated: true)
        if controller.navigationController?.viewControllers[ct] is UITransitionViewController {
            controller.navigationController?.transitioningDelegate = controller.navigationController?.viewControllers[ct] as! UITransitionViewController;
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接