Exploring Android WebView with AJAX and accessing local files

I'm facing an issue with my android webview as it loads a website locally stored in my assets. The problem arises when certain parts of the website use jquery $.ajax-gets to fetch HTML to display in a modal, resulting in cross-domain problems. Despite extensive research and troubleshooting, including checking the manifest file for necessary permissions, I haven't been able to resolve this issue.

Running on a Nexus 7, the files are situated in the assets folder (file:///android_asset). While everything else functions correctly, the ajax GET requests continue to pose a challenge.

The relevant code in the manifest includes:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Key webview settings include:

mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
mWebView.addJavascriptInterface(this, "android");
if (savedInstanceState != null) {  
    mWebView.restoreState(savedInstanceState);
} else {          
    mWebView.loadUrl("file:///android_asset/site/index.html");
}    

Regarding the javascript code:

var load = function ( source, callback, dontShowLoader ) {
if( !dontShowLoader ) {
    loading( 'show' );
}
$.ajax({
    url: source,
    type: 'GET',
    data: {
        campaign: true
    },
    success: function ( data ) {
        var $data = $(data);
        loading( 'hide' );
        $data.data( 'url', source );
        callback( $(data) );
    }
});
};

Is there something crucial that I might be overlooking? Is it truly impossible to perform ajax GETs over local file content? Keep in mind that I only have access to the local files, as the application is often used offline without an internet connection.

Answer №1

For successful execution, it is important to enable crossdomain access. The following code snippet illustrates how to allow crossdomain for both JSON values and scripts:

$.ajaxPrefilter( "json script", function( options ) {
    options.crossDomain = true;
});

Answer №2

Special thanks to @njzk2 for providing the solution:

$.ajaxPrefilter( 'text', function( options ) { options.crossDomain = true; }); 
$.ajax({ url: source, type: 'GET', dataType: 'text'

To ensure functionality across different browsers like Firefox, Chrome, and IE when loading a local file (without using a server), I added the following code:

I found that adding this specific parameter targeted api 16 or higher (still exploring if there are other parameters for older APIs):

mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

Thank you for your assistance!

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

The jQuery validation feature permits entering a code that falls within the range of user1 to user100

Here is an example where the user can only enter a code between 1 and 100. Otherwise, it will return false. var regexCode = /var regexEmail = /^0*(?:[1-9][0-9]?|100)$/; $(document).on('change','#code',function() ...

Are memory leaks in Android caused by instance variables?

After creating an Android application with a FragmentActivity and multiple fragments, each with their own associated view and logic encapsulated in separate classes for complex calculations, I encountered a challenge. The results of these calculations need ...

What is the best way to fill cascading dropdown lists with data fetched through ajax requests?

I attempted to create a CRUD web page with two cascading dropdown lists. Everything works smoothly when saving the data, but when retrieving it, the second dropdown list remains empty. Even after trying to populate the second dropdown list once the code i ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

Retrieve the Express session using the session ID (sid)

I am faced with the challenge of setting up multiple websocket servers that interact with users through a centralized http server. When a user logs in, the Express program creates a session and stores the username within it. The user is then directed to a ...

Tips for testing the speedometer on an Android device

I just finished developing an Android speedometer app and I'm looking for ways to test it on a virtual device. Does anyone know if there's a way to do this? Alternatively, are there any other methods for testing the app that you recommend? Thank ...

Getting complete contact information from a device into a checkbox with a selectable name can be achieved by following these steps:

Hi there, I am new to android development and struggling with coding. I need to create a dynamic growing list of checkboxes that display the full contact list on my device. The checkboxes should be selectable and already selected, and they should grow dy ...

Utilizing React to retrieve API data and implement search input filtering with autocomplete functionality

Hey there, I have a query regarding a React filter search input component. Currently, I am working with two components: FirstPageComponent.js import React from "react" import AutoComplete from "./AutoComplete" export class FirstPageComponent extends Re ...

The current export script is experiencing difficulties when working with the next/image component

I am working on a project that I need to build and export, but I am facing an error during the process. Below is the build script found in my package.json file: "scripts": { "build": "next build && next export" } ...

Expanding Height Issue with AnimatedVisibility in Jetpack Compose Dialog

So I have encountered a situation in my project where I am using a composable component... @Composable private fun ShowDialog() { var showText by remember { mutableStateOf(false) } val text = if (showText) { "Hide Text&q ...

Change the structure of the JavaScript object into a new format

I humbly ask for forgiveness as I am struggling with figuring out how to accomplish this task. It seems like we need to utilize a map function or something similar, but I am having difficulty grasping it. Below is the object 'data' that I am wor ...

Leveraging the power of map in an Angular typescript file

I've been attempting to populate a Map in Angular by setting values dynamically. When certain buttons are clicked, the onClick function is invoked. typeArray: Map<number,string>; Rent(movieId: number){ this.typeArray.set(movieId,"Rental ...

Adding custom data attributes to HTML tags in Vue.js

I have a question regarding adding a data attribute to the <html> element in vue.js (v2). I haven't been able to find any guidance on how to do this in the auto generated code or the documentation. The end goal is to achieve this desired output ...

Ensure that divs remain in a static position within the dialog box

Within the jQueryUI dialog, I have gray boxes at the top and bottom of the visible area represented by the .nav elements. I want these gray boxes to stay fixed in their position even when scrolling within the dialog. Despite setting position: absolute, the ...

Mastering the manipulation of complex nested objects within React state

Welcome, fellow developers! I am a junior developer currently working on a project that involves a large nested object structure (see example below). I am looking for the best approach to use this as a React state that can be accessed from multiple compon ...

Tips for Storing Your Data Collection: A Guide on Different Storage Options

In the different parts of my app, I require access to a dataset containing timezones. Traditionally, I have stored such data in a class method like Timezone.all_zones (Ruby) for easy accessibility anywhere in my code. Is there a way to achieve this same ...

Can you explain the purpose of the bson type in conjunction with the javascript/javascriptwithscope?

I am intrigued by the utilization of the two types of bson, specifically javascript and javascriptwithscope, as the foundational types of bson. What are the use cases for these types and how can a javascriptwithscope object be created and saved in mongodb ...

Retrieving DOM Element in Angular from Freshly Loaded Template

Recently starting my journey with Angular, I have encountered a challenge when trying to access the DOM from a newly loaded template. Let me explain what's going on - index.html <div class="template" ng-app="myApp" ng-controller="myController"> ...

Troubleshooting AngularJS binding problem when using ngRepeat to handle Collapse and Expand Caret icon

I am experimenting with implementing collapsible and expandable panels within an ngRepeat loop. Here is my approach: <tbody ng-repeat="item in Items"> <tr data-toggle="collapse" class="accordion-toggle"> <td>{{item.name}}< ...

Tips on using regular expressions to divide strings based on the pattern of "{{variableValue}}" surrounded by spaces

I'm struggling to create a regex pattern to split strings correctly. Opening line: {{ text1 }} 123 {{text1}}{{text1}} {{ text1}}134 Variable text content: const a = text1; Splitting outcome: ["{{text1}}"," 123 ","{{text1 ...