Search code examples
cordovavisual-studio-cordovacontent-security-policyapache-cordova

Visual Studio 2015 Ajax Request fails using Device in Apache Cordova Android platform 6


Team Apache,

This question I am posting, while trying all available resources about ajax request failed in TACO in Vs 2015. I am using API with localhost, used IP address of localhost , tried with server hosted API, but I always get status = 0. when I use DEvice for Android. With Ripple Nexus it work fine.I am struggling for a week and no luck yet.

I am using VS 2015 , Android platform 6.

I have added whitelist plugin as well, and tried to add all type of access origin:

<access origin="*" />

OR

<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />

Added meta tag:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

Solution

  • Lollipop introduced a number of changes to the Android security model. To support the new model, Cordova 5+ introduced the whitelist plugin and a new security model that deprecated <access origin="*">. Your app has all the right pieces, but you haven't configured them correctly.

    1. Whitelist plugin
    2. Content Security Policy (meta tag) declares what resources can be accessed in the client-side code
    3. <allow-intent> tells the native/compiled app what sources can be used for data (e.g. XHR)
    4. <allow-navigation> tells the native/compiled app what sources can be used for content (e.g. full page navigation)

    Note that the CSP and <allow-intent/navigation> tags must match. The CSP is used by your client-side code in the webview. The <allow-intent/navigation> tags are used by the native/compiled app wrapper.

    To enable data access to domains outside of the app itself, you need to modify your content-security-policy (CSP) to identify the outside authority. There's an excellent tutorial available here, but I've provided an example below. This CSP allows XHR requests and content to be loaded from https://thecatapi.com (a silly API that returns cat images):

    In index.html...

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' content-src: https://thecatapi.com data: gap: https://ssl.gstatic.com https://thecatapi.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
    

    In config.xml...

    <allow-intent href="https://thecatapi.com/*" />
    <allow-navigation href="https://thecatapi.com/* />