当前位置: 代码迷 >> JavaScript >> iOS UIWebView应用程序在Safari中打开链接
  详细解决方案

iOS UIWebView应用程序在Safari中打开链接

热度:159   发布时间:2023-06-12 14:37:37.0

我有一个只有一个视图的iOS应用程序,即UIWebView(它打开了应用程序的主要内容)。 我想在某处(例如在表格行上)单击时,在Safari浏览器中而不是在UIWebView内打开特定链接。

是否可以在不编写任何iOS代码的情况下做到这一点,而不是使JavaScript在Safari本身中打开该链接?

我有那个代码,但是根本没有帮助:

HTML代码

<tr class='link-to-pdf' data-href='www.example.com'>

JS代码:

 $(".link-to-pdf").click(function () {

            var a = document.createElement('a');
            a.setAttribute("href", this.getAttribute("data-href"));
            a.setAttribute("target", "_blank");

            var dispatch = document.createEvent("HTMLEvents");
            dispatch.initEvent("click", true, true);
            a.dispatchEvent(dispatch);

        });

在某些情况下,您可以告诉javascript中所有具有target="_blank" ,并使用'_system'参数将它们传递给window.open。 这将适用于iOS和Android。

$(document).on('click', 'a[target="_blank"]', function(ev) {
  var url;

  ev.preventDefault();
  url = $(this).attr('href');
  window.open(url, '_system');
});

或者,您只需替换a.setAttribute("target", "_blank"); 带有a.setAttribute("target", "_system");

这在一个古老的项目中对我有用,但是不确定它是否仍然有效(在iOS和Android上)

如果以上答案对您不起作用,您可以通过iOS方式解决。 为此,您需要实现webView:shouldStartLoadWithRequest UIWebViewDelegate协议方法来检查URL。

 - (BOOL) webView: (UIWebView *) theWebView shouldStartLoadWithRequest:(NSURLRequest *) request navigationType: (UIWebViewNavigationType) navigationType
{
    NSURL *url = [request URL];
    // check URL in your if condition
    if (...) {
        //open URL in Safari
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    }
    else
        return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
}

上面的答案有一个约束,您需要实现从JQuery通知ios应用程序的机制,此处讨论了可能的解决方法: :

  相关解决方案