The Android webview encountered an error: XMLHttpRequest failed to load because the specified Origin <url> is not permitted by Access-Control-Allow-Origin restrictions

I have developed an application that loads an entire website in an Android WebView. The native code in the Android project communicates with the webpage using the Android Jockey Library, and vice versa.

Everything is working smoothly except for one instance where I encounter the error:

XMLHttpRequest cannot load ... Origin <url> is not allowed by Access-Control-Allow-Origin
. This occurs when the website loaded in the WebView makes an ajax call to the backend API.

My website is hosted at m.mywebsite.com which makes ajax calls to api.mywebsite.com, both are separate sub-domains. Interestingly, this setup works fine on iOS.

I am currently testing this on Android v4.4.2. I have tried compiling against target SDK 15 and 19 but it didn't make any difference.

I have configured my WebView with the following settings:

webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setBuiltInZoomControls(false);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAllowContentAccess(true);

    webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    webView.getSettings().setAllowFileAccessFromFileURLs(true);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().setAppCacheEnabled(true);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
    }

    webView.getSettings().setSupportZoom(false);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setInitialScale(0);

And here is how I integrated Jockey:

if (Utils.isNetworkAvailable(this)) {
        jockey = JockeyImpl.getDefault();
        jockey.configure(webView);
        webViewClient = new MyWebViewClient(this);
        jockey.setWebViewClient(webViewClient);

        setJockeyEvents();
        webView.loadUrl(EnvironmentManager.getStartUpURL());
    } 

Has anyone else encountered a similar issue or found a solution to this problem?

Thank you!

Answer №1

Hello there! It seems like you may need to adjust a setting for your web view. This issue typically occurs with devices that have an API level greater than 16. Please review the code snippet below:

if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
  webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}

I hope this solution resolves the issue for you.

Answer №2

To address this issue, consider setting the Access-Control-Allow-Origin header in the page hosted on api.mysite.com. Here is an example of how you can implement it:

Access-Control-Allow-Origin: http://mobile.mysite.com

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

Tips for extracting parameters from a JSON String using JavaScript

When attempting to parse a JSON String, I am encountering an issue where the parsed value is coming up as undefined. You can view the code on this jsfiddle link. <input type="submit" onclick=testJSON() value="Test"/> <div i ...

Adding JavaScript in the code behind page of an ASP.NET application using C#

Currently, my challenge involves inserting a javascript code into the code behind page of an asp.net application using c#. While browsing through various resources, I stumbled upon some solutions provided by this website. Despite implementing them as inst ...

Utilizing the datepicker options function within a different function

I'm working on a function that utilizes a promise to retrieve data from an asynchronous ajax call: $("#mySelect").on('change', function() { var mySelectValue = $('#mySelect').val(); var promise = getAvailableDates(mySe ...

Using jQuery AJAX to show user input field information

I am currently experimenting with using jQuery ajax to gather data from a form and then display the data using print_r. Here is an example of my index.php file: <!DOCTYPE html> <html> <head> <title>CRUD application wit ...

Is there a way to prevent mouse wheel scrolling on a React "number" input field?

Currently, I am encountering an issue with MUI type="number" textfields. When I focus on the field and then scroll the mousewheel, the input value changes unexpectedly. I have looked into adding a blur function after scrolling to prevent this, but I would ...

What is the process for determining the files array in the nx dep-graph?

With each new release of NX v16.1.4, the file node_modules/.cache/nx/nxdeps.json is created. The structure of this file differs from the one generated by nx graph. In previous versions up to 16.1., the file contained an array named nodes.<app/lib>.d ...

An error popped up while using the fetch API due to an unexpected end of input

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?tag=platform&limit=100&format=json', { method:'GET', mode:'no-cors', dataType: 'json', headers: { 'Accept': 'a ...

Retrieve content inside an iframe within the parent container

Hey there! I've been working on adding several iframes to my webpage. Each iframe contains only one value, and I'm trying to retrieve that value from the parent page. Despite exploring various solutions on Stack Overflow, none of them seem to be ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Creating dynamic HTML table rows with data from a JSON object

Query: In search of a Jquery or JavaScript solution for generating dynamic table rows with colspan using the JSON structure provided below. I am encountering difficulties in creating the necessary rows and have attempted several approaches without success ...

Error encountered upon initializing Node-RED due to the presence of an unexpected token while incorporating the NPM module "file-exists" into the

Currently, I'm in the process of developing an application using Node-RED and I'm looking to incorporate some NPM modules into my project. One particular module from James Thom caught my attention, called node-red-contrib-npm, which automates the ...

What is the best way to establish communication between methods in a React application?

In the SelectedTopicPage component, I currently have two methods: navigateNext and render. My goal is to pass the value of topicPageNo from the navigateNext method to the render method. What is the best way to achieve this in React? When I attempt to decla ...

"Is there a way to transfer a value from one list box to another without needing to refresh the page, by utilizing AJAX,

Is there a way to automatically load Related Course levels in the Course Level Listbox when selecting a Course from the Course list? <script type="text/javascript" src="js/jquery.js"></script> <div>Course:<select name="course_id" id= ...

Different ways to determine if a given string exists within an Object

I have an object called menu which is of the type IMenu. let menu: IMenu[] = [ {restaurant : "KFC", dish:[{name: "burger", price: "1$"}, {name: "french fries", price: "2$"}, {name: "hot dog", d ...

Unexpected behavior: Controller action method retrieves undefined value upon jQuery Ajax request

I'm currently working on my ASP.NET Core 3.1 project and implementing cascading dropdown functionality with jQuery. I've set it up so that changing the value of the first dropdown (Region) should automatically update the second dropdown, Location ...

Move items between two tree views using Javascript and jQuery drag and drop functionality

Recently, I have been on a quest to find drag and drop functionality for moving tree listing items between two separate tree views. While I did come across some solutions that work within a single tree, I have yet to find one that specifically caters to tr ...

Issue with onblur and focus while returning back from external window

Instructions to reproduce the issue: Important: Set up two input fields with names and add a console.log("Test Focus In" + element.getAttribute("name")) and console.log("Test Blur" + element.getAttribute("name")) statement in the focusin and blur event f ...

Clear all CSS styles applied to a targeted division

My website built on Wordpress links to several CSS files. One specific div has its own unique style that is separate from the main Wordpress styles. Unfortunately, the Wordpress CSS ends up interfering with my custom div's layout. Is there a way in HT ...

Issue with accessing data from database in my app

I am currently working on a project that involves retrieving data from my database. The user inputs a car registration number and a rating (ranging from 1 to 5) and then clicks a button. Upon clicking the button, my code is supposed to execute, fetching te ...

Extracting information from JSON and presenting it in a structured table format

I've hit a wall with this JavaScript issue on my website. I'm trying to convert API JSON data into a table, and it's working fine when the data is on separate lines. However, when I introduce nested arrays in the JSON data, everything ends u ...