Remove browser data in PhoneGap / Prevent PhoneGap from utilizing cookies

Currently, I am in the process of creating a login system for my mobile application. After logging in to my server, it sends back a JSESSIONID that I can utilize for further authentication. The issue I am encountering is that PhoneGap is automatically storing this cookie without my explicit consent. As a result, I am unable to implement a log out feature since PhoneGap retains the cookie and includes it in every call I make to the server. I am using xmlhttp requests. I am seeking a solution to either remove this cookie or prevent PhoneGap from storing it initially, allowing me to manage the session cookie on my own. Despite my efforts, I am unable to locate this cookie. Does anyone have suggestions on resolving this dilemma?

Answer №1

To start, create the CacheCleaner class (CacheCleaner.java file) within the package "org.apache.cordova.plugins"

package org.apache.cordova.plugins;

            import java.io.File;

            import org.apache.cordova.CallbackContext;
            import org.apache.cordova.CordovaPlugin;
            import org.apache.cordova.PluginResult;
            import org.json.JSONArray;

            import android.util.Log;
            import android.widget.Toast;

            public class CacheCleaner extends CordovaPlugin {

                public static final String LOG_PROV = "PhoneGapLog";
                public static final String LOG_NAME = "CacheCleaner Plugin";

                @Override
                public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) {
                    if (action.equals("del")) {
                        cordova.getThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    final File dir = cordova.getActivity().getCacheDir();
                                    if (dir != null && dir.isDirectory()) {
                                        deleteDir(dir);
                                        showToast("Cache is deleted.","short");
                                    }
                                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.e(LOG_PROV, LOG_NAME + ": Error: " + PluginResult.Status.ERROR);
                                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
                                }
                            }
                        });
                        return true;
                    } else {
                        Log.e(LOG_PROV, LOG_NAME + ": Error: " + PluginResult.Status.INVALID_ACTION);
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
                        return false;
                    }
                }

                public static boolean deleteDir(final File dir) {
                    if (dir != null && dir.isDirectory()) {
                        final String[] children = dir.list();
                        for (int i = 0; i < children.length; i++) {
                            final boolean success = deleteDir(new File(dir, children[i]));
                            if (!success) {
                                return false;
                            }
                        }
                    } else if (dir != null && dir.isFile()) {
                        dir.delete();
                    }
                    return true;
                }

                private void showToast(final String message, final String duration) {
                    cordova.getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(duration.equals("long")) {
                                Toast.makeText(cordova.getActivity(), message, Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(cordova.getActivity(), message, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }

Next, create a javascript file named "cachecleaner.js"

cordova.define("cordova/plugin/cachecleaner", function (require, exports, module) {
                var exec = require("cordova/exec");
              module.exports = {
                    del: function (win, fail) {
                    exec(win, fail, "CacheCleaner", "del", []);
                    }
                };
            });

Be sure to add the following line to your "config.xml" file within the res folder of your Android project.

<feature name="Share"><param name="android-package" value="org.apache.cordova.plugins.CacheCleaner" /></feature>

Finally, use the provided code in your HTML file to clear the cache when a button is clicked.

Here's the function to use:

 $(document).on('click','.abs',function(){
             var cachecleaner = cordova.require("cordova/plugin/cachecleaner");
              cachecleaner.del(
                function () {
             console.log("PhoneGap Plugin: CacheCleaner: callback success"); 
              window.location.href = "index.html";             
                },
                function () {
                  console.log("PhoneGap Plugin: CacheCleaner: callback error");
                }
              );

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

Executing a Python script within a Django project by clicking on an HTML button

There's a Python script file located in a Django project, but it's in a different folder (let's call it otherPythons). I'm looking to execute this Python file when an HTML button is clicked using JavaScript. Only looking for solutions ...

Module specifier "vue" could not be resolved due to an uncaught TypeError. Remember that relative module specifiers must always begin with "./", "../" or "/"

Looking to create the most basic vuejs Hello World application using separate files. Here is the project setup: start by creating index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Error encountered during decryption with AES encryption: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH'

I am attempting to decrypt data retrieved from MongoDB using a key and initialization vector (IV) that were stored in an environment function. However, I keep encountering the following error: ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH app.get("/recieve", as ...

Display and conceal button while scrolling in both directions

Seeking assistance with solving a coding challenge. I have created a function that reveals a button (an arrow pointing from bottom to top) when scrolling down. Now, I aim to implement another feature where the button appears after scrolling over 500 pixe ...

JQuery Menu with Broken UL Formatting on Windows versions of IE and Firefox

Hey there! I've been struggling with a menu design that works perfectly on Mac browsers but is completely broken on Windows. I've spent hours trying to fix it and would really appreciate if a kind programmer could take a look and help me out. The ...

Are there gaps in the Android online API documentation?

I've noticed a peculiar trend in the Android online API documentation where many methods appear to be left undocumented, such as the one at http://developer.android.com/reference/android/app/ProgressDialog.html#setProgress(int). It seems unlikely that ...

The Android 6.0 update brings a touch of holo design to the PreferenceFragment module

I'm having an issue with the design of my Android 6.0 phone's PreferenceFragment. It seems to have a mix of Holo and Material design elements, and I want to change it to a sleek Material design. However, I'm unable to make the necessary chan ...

Is there a way to send the image's name as a parameter?

I am facing a challenge in achieving a specific task and need some guidance. My current approach involves passing the image name as a parameter to the cancelimage.php script, but it seems like I am not utilizing the variable 'image_file_name' cor ...

using a ternary operator within the map function

Currently, I'm developing a web application that allows users to view a list of items and mark certain items as favorites. The favorites are stored in an array of IDs assigned to a prop (this.props.favorites). To ensure there are no duplicate entries, ...

Exploring Android: The Comparison of Implicit Intents and Broadcast Receivers

As I delve into the world of Android development, I find myself confused about the difference between an implicit intent and a broadcast receiver. I seek clarity on how to distinguish these concepts and when it is appropriate to use each one. Both play a ...

Utilizing Directional and Spotlight Lighting with ThreeJS Helper Functions

I am currently utilizing a guide on implementing light in Threejs from Light in Threejs. I have successfully added some light to my scene. Now, I am attempting to add light to the character in my game but it is still not working. Even though I used the co ...

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Utilizing Soundcloud API Authentication in Angular.js: A Step-by-Step Guide

I've been able to successfully use the public Soundcloud API, but I'm struggling with implementing the callback.html in order to display the login dialog. For my App on Soundcloud, the callback redirect uri is set to: http://localhost:8080/#/cal ...

Android app experiencing issues with field updates

I'm facing an issue with the code below - when I input the data and hit save, it doesn't get saved to the database. What could be going wrong here? Snippet from IMService.java @Override public String updateUserDetails(String username, String st ...

"Use the data-attribute to dynamically append a child element to the

Here are a couple of divs that look like this: <div id="thisisme" data-order="1"> <div id="thisisme" data-order="2"> I am looking to insert some content into the specific div with data-order = 1. The following Javascript code is what I have t ...

Sending user input from search component to main App.js in React

I'm currently working on an app that searches a Movies database API. I have a main fetch function in App.js, and in tutorials, people are using a search bar within this main APP component. I'm wondering if it would be better to create a separate ...

Exploring the journey of History.js and Same-Origin Policy leading to HTTPS encryption

Utilizing history.js, I am attempting to push a state change from an HTTP site like: http://www.example.com/some/resource ...to a secure site (payment page), such as: https://www.example.com/payment/for/some/resource However, Safari is throwing thi ...

Converting a PHP variable to JSON in an AJAX call

At the moment, my approach involves using a jQuery Ajax asynchronous function to repeatedly request a PHP page until a large number of spreadsheet rows are processed. I am uncertain if the way I set the variables to be passed to the requested page is corre ...

Manipulating arrays of objects with handlebars.js

I need help with my node.js app that is returning JSON data for computers. { computers: { john: { cpu: "intel", ram: "8MB", hd: "1TB" }, jane: { cpu: "intel", ram: "12MB", hd: "500GB" }, mary: { ...

Tips for showing the React-Select array label in a text field

I'm a beginner in the world of React and I've encountered a puzzling issue. I'm attempting to showcase the selected value from a dropdown component in the adjacent text field in my React project. Can anyone guide me on how to achieve this? ...