The Haskell WARP/WAI server is not sending responses to AJAX requests made from an Android embedded WebView

UPDATE 3 After testing the endpoint , I found that the request returns successfully. This indicates that there might be an issue with my Haskell Warp+WAI application server.

Could anyone suggest why a server API call would work for most browsers but fail in Android WebView?


To clarify, I want to emphasize that I am not making cross-domain requests. Despite numerous questions regarding that issue, my AJAX request is directed to the same domain where the WebView is loaded.

UPDATE 2 Instead of using jQuery, I opted for the more basic method using xhr:

function pingServer()
{
  var xhr = new XMLHttpRequest();
  xhr.open('get', URL + 'ping');

  // Track the state changes of the request.
  xhr.onreadystatechange = function()
  {
    var DONE = 4; // readyState 4 indicates that the request is complete.
    var OK   = 200; // status 200 represents a successful return.

    if (xhr.readyState === DONE)
    {
      if (xhr.status === OK)
      {
        $('#submitDialog p').text(xhr.responseText + ' : ' + xhr.status);
      }
      else
      {
        $('#submitDialog p').text(xhr.responseText + ' : ' + xhr.status);
      }
    }
  };
  xhr.send(null);
}

However, this method was unsuccessful. The xhr.responseText is empty and the xhr.status is 0.

I suspect that something may be wrong with my server setup. I'm utilizing a unique server - the Haskell-based WARP with WAI. But, if that's the case, then why does everything work smoothly in other browsers?


UPDATE Upon debugging, I encountered the following error with the AJAX call shown below (a simple query to check server connectivity):

Error: NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load ''

It's worth mentioning that the actual URL I'm using loads without issues in any mobile or desktop browser, except for the Android WebView!


I have developed a basic Android application consisting of a WebView that loads a remote URL (not a local resource). Everything works fine, except that all my AJAX calls trigger the error callback immediately. Testing has been conducted on a Samsung Galaxy S6 device, targeting SDK version 21.

The failed AJAX call looks like this, with others sharing similar properties:

$.ajax(
{
  url: URL + 'ping',
  cache: false,
  async: false,
  timeout: 5000,
  error: fail,
  success: transmitScore
});

Both transmitScore() and fail() functions are defined elsewhere within the scope.

This is the configuration of my WebView:

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.Locale;

public class Example extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.main);

        WebView wv = (WebView) findViewById(R.id.webview);

        wv.setWebViewClient(new WebViewClient()
        {
            public void onPageFinished(WebView v, String s)
            {
                v.loadUrl("javascript: setLang('" +
                    Locale.getDefault().getLanguage() + "')");
            }
        });
        wv.getSettings().setJavaScriptEnabled(true);
        wv.loadUrl("http://example_url_for_privacy:2753/application");
    }
}

If anyone has insights into what may be causing these issues, please share. The AJAX calls function properly in desktop Chrome and Android Chrome.

I've noticed many queries related to AJAX calls to local resource files requiring cross-domain permissions, but that does not apply in my scenario. All resources reside on the remote server, and all AJAX calls point towards it.

I also attempted setting my WebView to use WebChromeClient without observing any changes. It seems that nowadays, this is the default behavior for WebViews. In the AJAX calls, I experimented with various combinations of async and cache, yet none proved successful.

Answer №1

The issue was identified as the WebView loading the webpage using an IP address, while the JavaScript on the page referenced it by domain name. Although this might seem like a basic mistake to avoid, observing how other clients without the Webview functioned properly initially led me to dismiss it as a potential problem.

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

Inquiries regarding the vuex dynamic registration module result in a complete refresh of all Vue components

When trying to create a new Vue component, I encounter the issue of having to call store.registerModule() before creation. However, this action results in all existing Vue components being destroyed and recreated. The same issue happens when using store. ...

Using Node.js to display the outcome of an SQL query

I have been attempting to execute a select query from the database and display the results. However, although I can see the result in the console, it does not appear on the index page as expected. Additionally, there seems to be an issue with the way the r ...

Show complete items in Vue.js

Issue at hand: I am in need of displaying and potentially changing JSON data. My goal is to present it in a directory tree format. The structure of the object is unknown, it could be something like this: "buttons": { "login": "LOGIN", "register": ...

Rendering template and data from a promise in AngularJS: A comprehensive guide

Hey there, I'm diving into the world of Angular and I've been struggling for the past couple of days trying to figure out a solution for this issue. Not entirely sure if my approach is right either. My goal is to create a simple page with a dyna ...

Why is it that when I use XMLHttpRequest for a menu and request a page with HTML that contains JavaScript, nothing happens?

Below is the code snippet I'm using for a menu in a webpage I am currently developing. In some cases, the page I want to request contains JavaScript, but when the requested page is loaded into the actual page, the script does not run. //Ajax menu all ...

I'm feeling stuck trying to iterate through this array, especially when the console keeps saying it's actually an object

As I embark on a personal project to fetch and display information from Reddit, I find myself confused by an error that keeps popping up. There are two main points of confusion for me. The issue arises when the page fails to render due to the message ...

Getting the ID name from a select tag with JavaScript - A quick guide!

Can you help me retrieve the id name using JavaScript when a selection is made in a select tag? I have tried running this code, but it only alerts undefined. For instance, if I select bbb in the select tag, I should be alerted with 2 Any suggestions on ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

What is the process of segregating an array of objects utilizing the map method?

Struggling to form an array of objects within another array of objects based on ID. I successfully grouped the objects by "applicationId," but am facing issues with grouping the internal arrays of attributes and values. Additionally, the current code is pr ...

Unable to view the most recent state

Looking at the code below: export function loginUserRequest() { console.log('ACTION INITIATED'); return { type: LOGIN_USER_REQUEST, }; } we can see the matching reducer: export default function loginReducer(state = initialState, acti ...

What is the proper way to include 'rowspan' specific CSS within an HTML table?

I have an HTML table with rowspans in it: table tr, td { border: 1px solid black; } tr:nth-child(1) { background-color: red; } tr:nth-child(2) { background-color: blue; } <table> <tr> <td rowspan=2>Section 1</td> ...

Unable to associate with 'paint' as it is not a recognized attribute of 'mgl-layer' while using mapbox in Angular 9

I am currently working on an Angular 9 project with the latest version of mapbox integrated. My goal is to toggle between displaying contours and museums on the map. To achieve this, I have installed the package: "@types/mapbox-gl": "^1.12. ...

Oops! It seems like there is an issue with reading the property 'filter' of an undefined object. Any ideas on how to resolve this error

Having an issue with a custom filter that is causing an error "ERROR TypeError: Cannot read property 'filter' of undefined". I need help fixing this as it's preventing anything from rendering on the page. Any suggestions on what changes I sh ...

Creating a custom "dashboard" to manage Fabric.js elements

This question revolves around a more general topic of Javascript rather than fabric.js. Currently, I am examining the "kitchensink" demo in Fabric.js. When you click on the "Object" tab and choose an item in the drawing area on the left, the control panel ...

Is there a way to modify my function expression without using any state variables?

Currently working on a jQuery game where the player is generated upon clicking a button. Below is the function expression I'm using to store the player's information: var getPlayerData = function() { return { name: $("#name").val(),/ ...

Troubles with displaying Google Maps on Ionic Modal

Having trouble displaying the google map in an ionic modal - it shows up fine on the page but not in the modal. Any help would be greatly appreciated, as this is quite frustrating. Below is my controller js and code for the ionic modal. $ionicModal.from ...

Scroll effect for read-only text input with long content inside a div

Is there a way to replicate the scroll functionality of a text input with readonly="readonly"? When the text exceeds the box size, you can highlight and scroll to view it all without a visible scrollbar. I am interested in achieving this effect within a p ...

Using CSS to create a transition effect for fading in and out background images

I created a website with a captivating full-page background image (img/bg_start.jpg): If you hover your mouse over the central animal on the page, the current image (img/bg_start.jpg) will fade out and be replaced with another picture (img/bg_start2.jpg) ...

What is the preferred method for initiating a call from a JSP to a servlet using an href link?

Currently, I am successfully using href to call a servlet URL. However, I would like to add parameters and receive a response from this request. Is it possible to achieve this? I attempted an AJAX call but encountered a CORS issue when trying to call an ex ...

Imagine if we forget to include parentheses when invoking a method by mistake

What happens if we don't include parentheses after calling a function, like in this scenario: renderContent(){} and then try to call it within a div <div>{this.renderContent()}</div> If we forget to add (), there will be no error display ...