12
votes

I am trying to open an external url link in my app which is a cordova app. Right now its presents an in app browser using modal view but it has NO back button or close button. The user essentially gets stuck when they click an external link. For instance, when someone clicks this link, enclosed in "Visit Website", an in app browser shows up, the website shows up fine, BUT there is no way to navigate back to the app, or close the in app browser. How do I go about fixing this?

<a href="http://www.sdtaproom.com/" target="_blank">Visit Website</a>

I saw that there is a solution, window.open("http://stackoverflow.com", "_system");, but I don't know how to implement it in the href code.

ANSWER (Edited): Add this code in the script tag in the head.

<script src="cordova.js"></script>
<script type="text/javascript">
window.addEventListener('load', function () {
  $(document).on('click', 'a[target="_system"],a[target="_blank"]', function (e) {
    e.preventDefault();
    var url = this.href;
    window.open(url,"_system");
  });
}, false);
</script>
3
You'll have to use javascript to pick all the links, and then pick the href and use it in the window.open functionjcesarmobile
can you please give an example in code?Josh O'Connor

3 Answers

20
votes

You can embed javascript code in the href attribute. This should do the trick:

<a href="javascript: window.open('http://www.sdtaproom.com/', '_system'); return false;">Visit Website</a>

You will also have to install the InAppBrowser plugin (don't be fooled by its name).

2
votes

as you can see here: all the solution in hybrid context aren't applicable on iOS and cordova/phonegap newer versions.

For this reason i suggest to use a native plugin, try this:

https://github.com/PaoloMessina/OpenUrlExt

this plugin use this code for Android:

navigator.app.loadUrl(<my_url>, {openExternal : true});

and a native Objective-C solution for iOS:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:<my_url>]]; 

This plugin is installable with plugman:

cordova plugin add https://github.com/PaoloMessina/OpenUrlExt

And really simple to use as specified in the github README

2
votes

Also bear in mind that if you have whitelisted the linked domain using the allow-navigation directive from config.xml, the window.open(url, '_system') solution will not work. (But you may want use some links to navigation and some others as external link).

In this case, you could use some link shortener service like bit.ly and link to that url instead of the original one.