27

I'm trying to open links in Safari (on an iPhone) from a PhoneGap application. I'm using PhoneGap version 3.1.0, and use PhoneGap Build, to build the application.

I have two links on the page (shown below in www/index.html). Both links open inside the PhoneGap application. I can see that PhoneGap is loaded correctly, because alert('device ready!'); is triggered.

What do I need to change, to open the links in the default browser (outside the app)?

The www/config.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>

<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" id="com.company.appname" version="0.0.3">
  <name>AppName</name>
  <description>description</description>
  <author href="http://www.example.com/" email="hello@example.com">
    Company
  </author>
  <preference name="phonegap-version" value="3.1.0" />
  <preference name="orientation" value="portrait" />
  <preference name="stay-in-webview" value="false" />

  <gap:plugin name="org.apache.cordova.inappbrowser" version="0.2.3" />
  <gap:plugin name="org.apache.cordova.dialogs" version="0.2.2" />
  <gap:plugin name="com.phonegap.plugins.pushplugin" version="2.0.5" />

  <plugins>
    <plugin name="InAppBrowser" value="CDVInAppBrowser" />
  </plugins>

  <feature name="InAppBrowser">
    <param name="ios-package" value="CDVInAppBrowser" />
  </feature>
  <access origin="*" />
</widget>

The www/index.html file looks like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <title>Test application</title>
</head>
<body>
  <a href="#" onclick="openUrl('http://www.google.com/'); return false;">Link test 1</a>
  <a href="#" onclick="window.open('http://www.google.com/', '_system', 'location=yes'); return false;">Test link 2</a>

  <script src="phonegap.js"></script>
  <script src="cordova.js"></script>
  <script src="js/jquery-1.9.1.js"></script>
  <script type="text/javascript">
    function openUrl(url) {
      alert("open url: " + url);
      window.open(url, '_blank', 'location=yes');
    }

    function onDeviceReady() {
      alert('device ready!');
    }
    $(function() {
        document.addEventListener("deviceready", onDeviceReady, true);
    });
  </script>
</body>
</html>

Here's the project structure:

├── platforms
├── plugins
│   └── org.apache.cordova.inappbrowser
│       ├── LICENSE
│       ├── package.json
│       ├── plugin.xml
│       ├── README.md
│       ├── RELEASENOTES.md
│       ├── src
│       │   ├── android
│       │   │   ├── InAppBrowser.java
│       │   │   └── InAppChromeClient.java
│       │   ├── blackberry10
│       │   │   └── README.md
│       │   ├── ios
│       │   │   ├── CDVInAppBrowser.h
│       │   │   └── CDVInAppBrowser.m
│       │   └── wp
│       │       └── InAppBrowser.cs
│       └── www
│           ├── InAppBrowser.js
│           └── windows8
│               └── InAppBrowserProxy.js
├── README.md
└── www
    ├── config.xml
    ├── cordova.js
    ├── index.html
    ├── js
    │   └── jquery-1.9.1.js
    └── phonegap.js
user2845946
  • 1,755
  • 29
  • 38
Martin
  • 2,302
  • 2
  • 30
  • 42
  • What is the issue here....??? – Mumthezir VP Nov 16 '13 at 04:21
  • @mvp I am guessing links wont open in Safari. – Jacob Nov 16 '13 at 06:05
  • here, in ur code u r trying inAppbrowser it'll open in another window inside app itself.. u want to open in browser right..? – Mumthezir VP Nov 16 '13 at 06:22
  • Yes, I want to open external links in default browser. Not inside the app itself. – Martin Nov 16 '13 at 10:44
  • have you got solution ??? – Piyush Nov 18 '13 at 10:02
  • I have the same issue. Have you got a solution on this? – Kingalione May 23 '14 at 18:12
  • Hi Martin check out on my question. There is a solution on this one which works on my application. http://stackoverflow.com/questions/23836560/open-a-link-in-the-default-browser-of-a-system-with-cordova-3-and-jquery-mobile/23836795#comment36680119_23836795 – Kingalione May 26 '14 at 21:40
  • Hello Martin, Did you ever find solution for this issue? I'm new to using phonegap and everything and I've done my first app already. Right now, I only have one little issue I can't seem figure out. I my app, I have several links which I would like to open using the phone default browser, right now it's not happening, the links are being open inside the app. I've followed many tutorials online but can't seem to figure out. Can you help? Thanks. – onlymushu Jun 03 '14 at 21:28
  • @onlymushu Sadly no. We ended up removing all external links from the final App, because we werent able to make this work the way we wanted it to. – Martin Jun 05 '14 at 08:32
  • I have a solution and made mine work! Thanks – onlymushu Jun 09 '14 at 18:24
  • @onlymushu Could you add an answer, with a description of how you made it work? – Martin Jun 10 '14 at 06:35
  • Check my 2015 answer here to open `_self` in WebView, and `_blank` in external browser: http://stackoverflow.com/questions/32208609/cordova-why-would-inappbrowser-plugin-be-required-to-open-links-in-system-brows/32227524 – Sebastien Lorber Aug 26 '15 at 13:39
  • This solution was ideal for me: [Solution] http://stackoverflow.com/a/16911921/4675328 – Toni Korin Sep 20 '15 at 09:08

16 Answers16

17

This is how i solved in Cordova/Phonegap 3.6.3

Install the inappbroswer cordova plugin:

cordova plugin add org.apache.cordova.inappbrowser

I wanted to keep my phonegap app as similar as possible to a standard web page: I wanted that by having target="_blank" on a link, it would open in an external page.

This is how i implemented it:

$("a[target='_blank']").click(function(e){
  e.preventDefault();
  window.open($(e.currentTarget).attr('href'), '_system', '');
});

so all i have to do is use a link like the following

<a href="http://www.example.com" target="_blank">Link</a>
pastullo
  • 4,171
  • 3
  • 30
  • 36
  • 1
    This solution work but what if i want to use another plugin crosswalk https://crosswalk-project.org/ instead of using default webview crosswalk make use of chrome engine as default webview so if i use inappbrowser plugin there is no point of crosswalk plugin what should i do? – Shersha Fn Jun 29 '16 at 15:49
10

How about this?

<a href="#" onclick="window.open(encodeURI('http://www.google.com/'), '_system')">Test link 2</a>

EDIT:

This may pertain: How to call multiple JavaScript functions in onclick event?

I was thinking, how about this:

Add to code:

$(".navLink").on('tap', function (e) {
    //Prevents Default Behavior 
    e.preventDefault();
    // Calls Your Function with the URL from the custom data attribute 
    openUrl($(this).data('url'), '_system');
});

then:

<a href="#" class="navLink" data-url="http://www.google.com/">Go to Google</a>
Community
  • 1
  • 1
Red2678
  • 3,177
  • 2
  • 29
  • 43
  • That link doesnt do anything on my iPhone - because onclick doesnt return false to prevent it from following the href="#". When I add return false (like this: Test link 2), Google opens inside the application itself: http://i.imgur.com/xKj1XZB.png – Martin Nov 19 '13 at 22:26
  • Changed to prevent default behavior – Red2678 Nov 19 '13 at 23:55
  • As you may have noticed, I had a openUrl method in the javascript I posted in my original comment. I can see that you call openUrl with two arguments, so I assume you're calling another method, and commented my own openUrl-method (which only takes one argument) out. When I test it out, nothing happens. – Martin Nov 20 '13 at 08:48
  • Your openURL function takes only 1 parameter. function openUrl(url) { alert("open url: " + url); window.open(url, '_system'); } – Red2678 Nov 20 '13 at 15:15
  • 1
    You should be change it to '_system' and remove the location parameter. – Red2678 Nov 20 '13 at 15:17
  • but it opens it in app only – Sopo Jul 06 '17 at 08:54
  • @Sopo that is what it is supposed to do. Might you be looking for this? https://stackoverflow.com/questions/38094005/cordova-open-a-link-using-google-chrome – Red2678 Jul 16 '17 at 18:59
  • thanks Red2678, but that issue i have solved using " gap : " https://stackoverflow.com/questions/44951834/cordova-plugin-inappbrowser-not-opening-links-from-app-to-ios-device-default-bro – Sopo Jul 17 '17 at 06:15
9

You should use the gap:plugin tag and the fully qualified id in your config.xml to install plugins:

<gap:plugin name="org.apache.cordova.inappbrowser" />

As documented here.

wildabeast
  • 1,723
  • 3
  • 18
  • 31
  • I have this line: , and I can see that it's added on the plugins tab in PhoneGap Build. http://i.imgur.com/e90CzMR.png. Do I need to remove the versionnumber? – Martin Nov 19 '13 at 22:05
  • 1
    AFAICT this doesn't open a link in the default browser. It opens in the in an InAppBrowser. That's not the same thing. For example when I'm the Facebook app and I click a link it opens the link in an InAppBrowser. If then have the option to also "Open in Safari". It's this second feature I'm looking for. Not an InAppBrowser – gman May 18 '15 at 09:44
  • @gman you need to pass the '_system' parameter to the window.open link to use the system browser instead of the inappbrowser. see Red2678's solution above. – wildabeast May 27 '15 at 21:16
7

I am using the cordova 6.0, here is my solution:

1: Install this cordova plugin.

cordova plugin add cordova-plugin-inappbrowser

2: add the open link in the html like following.

<a href="#" onclick="window.open('https://www.google.com/', '_system', 'location=yes');" >Google</a>

3: this is the most importaint step due to this I faced lots of issue: download the cordova.js file and paste it in the www folder. Then make a reference of this in the index.html file.

<script src="cordova.js"></script>

This solution will work for both the environment android and iPhone.

Tabish
  • 1,592
  • 16
  • 13
3

try with this below example.

<a class="appopen" onClick="OpenLink();">Sign in</a>


<script>
function OpenLink(){
    window.open("http://www.google.com/", "_system");
}
</script>

add this Below line in config.xml if you are using PhoneGap Version 3.1 or above

<gap:plugin name="org.apache.cordova.inappbrowser" />
Piyush
  • 3,061
  • 8
  • 34
  • 52
  • See this. Possible duplicate of this http://stackoverflow.com/questions/10244965/phonegap-opening-external-urls-in-safari/17849217#17849217 – Nijil Nair Nov 20 '13 at 09:28
  • @NijilNair I added the code: function openlink2() { var ref = window.open(encodeURI("http://www.google.com/"), '_system', 'location=no'); } and added a link: Another link. Google still opens inside the application itself: http://i.imgur.com/xKj1XZB.png – Martin Nov 20 '13 at 10:55
  • $(document).on("click", "#div_id", function() { var yourUrl = 'google.com/'; var ref = window.open(encodeURI(yourUrl), '_system', 'location=no'); }); Just try with a div instead of . You need to have an , since you are not passing any href. – Nijil Nair Nov 20 '13 at 11:43
  • Nothing happend when I did that. I tested it out in my browser (with succes), before using PhoneGap build, so I know it's not a javascript error. – Martin Nov 20 '13 at 13:36
  • @Martin have you face problem yet?? – Piyush Jan 24 '14 at 06:24
  • Sadly no. The deadline is long overdue, so we had to remove the feature in the app. :-( – Martin Feb 12 '14 at 19:51
  • Hey Martin..may i know which PhoneGap Version are you used in your application . if you are using 3.1 or above version PhoneGap then you must add Below line in your Config.xml. "" – Piyush Feb 28 '14 at 06:30
3

I had the same problem that you and the solution was include phonegap.js file to the <head> in all the pages where I will use the InAppBrowser.

All your code it's ok! The only thing you need add is: <script src="phonegap.js"></script> in your <head> section on your index.html

This is a little weird because Phonegap in his plugin documentation section says:

"If a plugin utilizes the js-module element to direct cordova to load the plugin javascripts, then no <script> references will be necessary to load a plugin. This is the case for the core cordova plugins"

And InAppBrowser is a core cordova plugin. But for some strange reason don't work until you include it the phonegap.js file (at least in 0.3.3 version).

NOTE: I found a bug. Some people says that you have to include 3 files: phonegap.js, cordova.js and cordova_plugins.js. But when I include this 3 files my app works fine in iOS 7, but in iOS 6 ignore the use of the plugin (Using: Cordova 3.3.0 + Phonegap Build + InAppBrowser 0.3.3).

You can see more in my SO question.

Hope this can help you!

Community
  • 1
  • 1
Jabel Márquez
  • 772
  • 1
  • 11
  • 38
2

Late answer but maybe it will be helpful for someone. So what I have in my working code in both iOS and Android application based on Cordova. To open external link in the default browser (Safari or Google):

1) Make sure that you have inAppBrowser plugin

cordova plugin add cordova-plugin-inappbrowser --save

2) Add to device.js

function openURL(urlString){
  let url = encodeURI(urlString);
  window.open(url, '_system', 'location=yes');
}

3) Create new link

<a href="#" onClick="openURL('http://www.google.com')">Go to Google</a>
1

For iOs, in your MainViewController.m do the following

- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if (![url isFileURL] && navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
            return NO;
        }
    } 

    return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType]; 
}

EDIT: For Android, in CordovaWebViewClient.java, in shouldOverrideUrlLoading do the following:

public boolean shouldOverrideUrlLoading(WebView view, String url) {
          if(/*check if not external link*) {
            view.loadUrl(url);
          } else {
            //prepend http:// or https:// if needed
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(i);
          }
          return true;
        }
Frane Poljak
  • 2,315
  • 23
  • 25
1

This worked perfectly for me on iOS.

As mentioned in the link above:

1- Install the plugin using the command:

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git 

2- And in the HTML file, use one of the following as needed:

window.open(‘http://example.com’, ‘_system’);   Loads in the system browser 
window.open(‘http://example.com’, ‘_blank’);    Loads in the InAppBrowser
window.open(‘http://example.com’, ‘_blank’, ‘location=no’); Loads in the InAppBrowser with no location bar
window.open(‘http://example.com’, ‘_self’); Loads in the Cordova web view 
Loukan ElKadi
  • 2,687
  • 1
  • 16
  • 20
1

I adapted pastullo's answer to work also in a WebApp that might be opened in a cordova InAppBrowser, but also als plain Web-App (e.g. for testing):

function initOpenURLExternally() {
    $("a[target='_blank'],a[target='_system']").each(function (i) {
        var $this = $(this);
        var href = $this.attr('href');
        if (href !== "#") {
            $this
                .attr("onclick", "openURLExternally(\"" + href + "\"); return false;")
                .attr("href", "#");
        }
    });
}

function openURLExternally(url) {
    // if cordova is bundeled with the app (remote injection plugin)
    log.trace("openURLExternally: ", url);
    if (typeof cordova === "object") {
        log.trace("cordova exists ... " + typeof cordova.InAppBrowser);
        if (typeof cordova.InAppBrowser === "object") {
            log.trace("InAppBrowser exists");
            cordova.InAppBrowser.open(url, "_system");
            return;
        }
    }

    // fallback if no cordova is around us:
    //window.open(url, '_system', '');
    window.open(url, '_blank', '');
}
Peter T.
  • 2,927
  • 5
  • 33
  • 40
0

This is how I got mine to work.

  1. In config.xml (phonegap) add <gap:plugin name="org.apache.cordova.inappbrowser" />
  2. My hrefs look as followed: <a onclick='window.open("http://link.com","_system", "location=yes")' href='javascript:void(0)' >link</a>
  3. Very important, what I was missing from the start, add the cordova script in your header: <script src="cordova.js"></script> I don't know why, but for me without it it don't work.

Hopefully that will help

onlymushu
  • 111
  • 2
  • 13
0

Might be it having a PATH environment variable problem, try this link it may be help.

Apache Cordova Documentation

Phonegap/Cordova – How to link to external pages

0

edit config.xml Add source= "npm" at plugin entry.'<'gap:plugin name="org.apache.cordova.inappbrowser" source="npm" > '

Sai
  • 1
  • 1
  • 2
    Hi! it would be splendid if you cold edit your answer to put the code example in a formatted code block and add a little explanation to it. – Jakob Runge Oct 11 '15 at 11:09
0

Instead of target="_blank", use target="_system" for the links you wish to open in an external browser (outside of the app). Then when clicking these links, your device will switch from your app to the system's browser app (ie. Safari or Chrome) to open the link.

-1

For those that didn't spot it in the original question you also need to make sure the URL you are trying to open isn't whitelisted by adding an access tag to your config.xml as follows:

<access origin="http://www.example.com" />

or you can do

<access origin="*" />

to allow anything

gamozzii
  • 3,911
  • 1
  • 30
  • 34
-3

In case you are trying to open link in external web browser try using class="external" for Anchor tag.

<a class="external" href="www.google.com" >Link</a>

Hope this helps!