iOS UIWebView app opens link in Safari

I have an iOS app which has only one view and that is UIWebView (It opens the main content of the app). I would like when I make a click somewhere(e.g on a table row) the app to opens specific link in Safari browser not inside the UIWebView.

Is that doable without writing any iOS code and instead of that make the JavaScript opens that link in Safari itself ?

I have thatcode,but it doesn't help at all:

HTML Code

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

JS Code:

 $(".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);

        });

Answers:

Answer

In some cases, you can tell all links in your javascript that have target="_blank", and pass them to window.open with the '_system' param. This will work on both iOS and Android.

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

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

Or in your case, simply replace a.setAttribute("target", "_blank"); with a.setAttribute("target", "_system");

This worked for me in an ancient projekt, but im unsure if it still works (on iOS and Android)

Answer

In case the above answer does not work for you you can fix it in an iOS way. For that you need to implement the webView:shouldStartLoadWithRequest UIWebViewDelegate protocol method where to check your 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 ];
}

There is a constraint with the above answer, you need to implement the mechanism of notifying the ios app from JQuery, possible workaround is discussed here: https://stackoverflow.com/a/11633460/3317354

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.