The InAppBrowser feature in Cordova is unable to access external URLs on iOS devices

Currently, I am in the process of developing a hybrid app using PhoneGap. The main issue I am facing is that when I click on a button on the index page, it should open an external URL. This functionality works perfectly on Android devices but fails on iOS.

I have searched for answers on these specific questions: iOS / Cordova: InAppBrowser not working, cordova/phonegap onclick doesn't work, PhoneGap Build: how to open external url in device browser on Android?, and phonegap open link in browser. Unfortunately, none of these resources provided a solution to my problem.


My first hypothesis is that there could be an error message alerting me of an issue. On the iPhone where I am testing the app, I received this error message:

[ERROR] Error initializing Cordova: Missing Command Error
.

The second possibility is that there might be something wrong with the event handling of the onclick event within the window.open method. When I click the open button on the iOS test device, nothing happens.

Below is the code snippet:

document.getElementById("openBrowser").addEventListener("click", function(){
        var ref = window.open('http://www.espn.com', '_self', 'location=yes');
         ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
         ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
         ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
         ref.addEventListener('exit', function(event) { alert(event.type); });
    });
<button id="openBrowser">Open</button>


The above piece of code works as expected and also functions properly on the Google Ripple emulator. Additionally, it works flawlessly on the Android platform. However, I cannot pinpoint whether the issue lies with the former or latter hypothesis mentioned earlier.

In addition, the cordova plugin inappbrowser is included in config.xml

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

Despite multiple attempts, I have been unable to identify the bug causing this malfunction. I have provided all the necessary information and hope to receive assistance in resolving this seemingly unsolvable problem.

The testing environments include Google Ripple Emulator, Phonegap Desktop App, and the Phonegap Mobile App. The desktop app creates the project directory while the mobile app and Google Ripple emulator connect to the desktop app for testing purposes. Interestingly, the external URL successfully opens on the ripple emulator but encounters errors on the mobile app, displaying an 'initialization error' upon launch.

Answer №1

After an extensive amount of time searching the internet, I finally managed to get InAppBrowser to open an external URL successfully. Here is the Stack Overflow answer that helped me fix my issue

Below is the code provided in the answer from the link:

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {

    // Mock device.platform property if not available
    if (!window.device) {
        window.device = { platform: 'Browser' };
    }

    handleExternalURLs();
}

function handleExternalURLs() {
    // Handle click events for all external URLs
    if (device.platform.toUpperCase() === 'ANDROID') {
        $(document).on('click', 'a[href^="http"]', function (e) {
            var url = $(this).attr('href');
            navigator.app.loadUrl(url, { openExternal: true });
            e.preventDefault();
        });
    }
    else if (device.platform.toUpperCase() === 'IOS') {
        $(document).on('click', 'a[href^="http"]', function (e) {
            var url = $(this).attr('href');
            window.open(url, '_system');
            e.preventDefault();
        });
    }
    else {
        // Leave standard behaviour
    }
}
<a href="http://stackoverflow.com">

The snippet above essentially checks whether the device is running on iOS or Android and uses a different method accordingly. This solution works seamlessly on both iOS and Android devices, as well as in a browser. Hopefully, this answer can assist others encountering similar issues.

Please note that the Device Plugin and InAppBrowser Plugin are necessary for this code to work correctly

Answer №2

After diligently researching online, I was able to resolve the issue with the InAppBrowser not opening external URLs properly. It turns out there was a bug in the InAppBrowser plugin specifically for iOS devices, causing an alert to appear when clicking on links. Fortunately, I managed to fix the problem by reverting to an older version of the plugin. Now everything is working smoothly as intended.

Answer №3

@Riccardo Check out the phonegap documentation for tips on using InAppBrowser. Make sure to add your code snippet inside the onDeviceReady function and give it a try!InAppBrowser

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

obtaining social media shares on Facebook through JavaScript

Below is the code I have written: function retrieveShareCount(url){ var count; $.ajax({ type: "GET", url: "http://api.facebook.com/method/fql.query?query=SELECT+share_count+FROM+link_stat+WHERE+url%3D%22http%3A%2F%2F9gag.com%2Fgag% ...

Executing Code Upon Module Load and Presenting It as Middleware

I am currently delving into the intricacies of how exporting and importing modules function in Nodejs. One of my tasks involves using a specific file to seed a mongodb database. Surprisingly, this file operates flawlessly and delivers the desired results ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

The Discord.js Avatar command does not support mentioning users

Everything seems to be working fine when I check my own avatar, but it doesn't work properly when I mention another user. Here's the code I'm using: client.on('message', message => { if (message.content === `${prefix}ava`) { ...

What is the best way to divide my Vue.js project into separate sections for development and testing purposes?

I am looking to split my vuejs frontend project into two sections: development and testing. For the development section, I want to work locally and make requests to the example:8010 url, while for the testing section, I need to send requests to the example ...

Exploring the nuances of useEffect() functionality and the impact of extra re-renders

I ran some tests using a dummy component and noticed an unusual pattern in the console output: Rendering: 0 Triggered: 0 Rendering: 4 Triggered: 4 Rendering: 4 I'm having trouble figuring out why this is happening. On the first render, the foll ...

Is it possible to include numbers and commas in JQuery Validation?

I have implemented a jQuery validation plugin to validate the fields of a form. One specific requirement is to validate a field to only allow commas and numbers. Below is the HTML code snippet: <input type="text" placeholder="Number of Employees" requ ...

Submitting form data including file uploads using AJAX

Currently, the file is being sent via AJAX using the following code: var fd = new FormData(); //additional actions to include files var xhr = new XMLHttpRequest(); xhr.open('POST', '/Upload/' + ID); xhr.send(fd); In ...

Load a certain script when another one is not accessible

In my index.html file, I have a script linked using <script src="..."></script> to be executed after the page loads. However, there are times when this script may not be available. In such situations, the client should load and execut ...

Retrieve information from XML Google Maps

I am currently facing an issue with my code that retrieves data from Google Maps in XML format. The problem I'm encountering is that it only displays the last set of data. How can I resolve this issue? You can find my code on jsFiddle function getli ...

Children components in Vue.js are receiving an undefined props object

Within my application, I am working with a parent and child component. The parent component directly includes the child component, which needs to access data from the parent. This data is fetched from a REST API within the parent component. However, when t ...

Duplicate an $sce generated entity and adjust its content

I am facing a situation where I have a variable structured in the following way: tableData1[$scope.tableHeadingsConstant[0]] = $sce.trustAsHtml('<div class="header12" id="runTitle0" style="cursor: pointer;">' + counter ...

Tips for correctly displaying diacritics with Webpack and Typescript

While working on my project, I encountered an issue with diacritics marks (such as German or Polish characters) when using Webpack with Typescript. Unfortunately, the problem arises when trying to display these marks in the console or on a webpage. It seem ...

What is the best method for submitting an ajax form post when it is dynamically loaded within a bootstrap modal window?

Need some help with a Bootstrap modal form that is not submitting via AJAX as intended. When the form is submitted, the entire page reloads instead of having the data posted in the background. How can I fix this while keeping the page state? Below is the c ...

What steps do I need to take to retrieve the passed slug in my API (slug=${params.slug})?

Is there a way for me to retrieve the passed slug in my API (slug=${params.slug}) while using the vercel AI SDK? const { messages, input, handleInputChange, handleSubmit, isLoading, error } = useChat({ api: `/api/conversation?slug=${params.slug ...

Cordova Emulate Android cannot locate Gradle or an installed Android Studio, despite their presence

Error Message After taking a break from the project and returning to it, I encountered an error message that I couldn't resolve no matter what solution I tried. Seeking help here as I know the app itself should be functioning properly. If you are un ...

cucumber-js Encounter with Illegal Token

I've been attempting to configure cucumber-js grunt and zombie. Following a tutorial, I encountered an issue when trying to run cucumber-js, as shown below: C:\webroot\Sari>cucumber-js C:\webroot\Sari\node_modules\zom ...

Error: React child must be a valid object

Currently, I am utilizing create-react-app with a websocketserver backend. The issue is arising as I am encountering the following error message: "Objects are not valid as a React child (found: object with keys {id, status}). If you meant to render a colle ...

Securing authentication in a custom backend using credentials provider with axios: A step-by-step guide

In my current setup, I have a Laravel backend that provides a JWT token. This token is then stored in the React frontend under signin callback using data.accessToken = data.access.token. To make calls to private endpoints, I can access this token and inclu ...

Error: Unhandled promise rejection: [object Boolean]

I am encountering an issue while trying to secure a route in my Angular application. Despite what I believe to be the correct implementation, I am facing an error message when the negative scenario is triggered: ERROR Error: Uncaught (in promise): [object ...