Utilizing Cookies in an AJAX Request for Cross-Domain Communication with Pure Javascript

I am in the process of developing an Analytics application and I'm seeking a method to uniquely identify each user's device. Currently, my approach involves generating a "cookie" from the server side to track all page clicks and interactions through Ajax requests.

The challenge I'm facing is that my analytics platform is hosted on xyz.com, while applications such as Abc.com and 123.com install my plugin (javascript) code. Upon initial visit, I create a cookie called "sha1" to distinguish each user/device. However, on subsequent requests, I need to verify with the server if the "sha1" cookie exists and take appropriate action accordingly. Unfortunately, due to making cross-domain Ajax calls, no cookies are being added to the request. I've explored options like setting "withCredentials=true" and "crossDomain=true," but have not been successful so far.

I am looking for a solution using Pure Javascript and would greatly appreciate any assistance or recommendations. I am also willing to consider altering my approach if a more practical and straightforward solution is suggested.

Answer №1

Below is an example of how I successfully used XMLHttpRequest() for CORS with cookie credentials in Chrome, FF 3.5+, Safari 4+, and IE10+. If you encounter any issues, it may be due to server configuration or browser compatibility.

// Sample GET request
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = 'application/json';
xhr.processData = false;
xhr.contentType = false;
xhr.onload = function() {
    // Handling successful request
    if (xhr.status == 200) {
        success(xhr.response);
    }
};
xhr.onerror = function() {
    // Denial of cross-domain request
    if (xhr.status === 0) {
        corsFailed(xhr.response);
    }
};
xhr.crossDomain = true;
xhr.withCredentials = true;
xhr.send();

Note that Safari and IE10+ require users to enable third-party cookies in their browser settings. There might be no alternative other than using custom headers instead of cookies and setting Access-Control-Allow-Headers on the server to include those custom headers. Additionally, ensure you have Access-Control-Allow-Headers set to include "Content-Type".

To support older browsers like IE8/9, consider implementing a fallback to XDomainRequest(), though keep in mind that it does not support cookie credentials.

The flags processData and contentType may only be necessary for POST requests. For my POST requests, I utilize FormData() objects instead of JSON.

Answer №2

To enable cross-origin resource sharing (CORS) in JavaScript, the headers must be modified on the server side:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With, X-Prototype-Version, Content-Type, Origin, Allow
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:http://yourdomain
Access-Control-Max-Age:1728000

The method to add these headers varies depending on the software used to serve the pages.

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

Is it possible to increase Google+ shares without needing an API key for every single page?

Looking to retrieve the number of Google+ shares for each URL on a search results page using Ajax. Facebook and Twitter share counts have been successfully implemented: $.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + & ...

Steps to activate an event when Windows is loaded

Every time windows load, I want to run $('select[name="order_id"]').change(), but it's not working as expected. After debugging in the browser console, I can see that the script $('select[name="order_id"]').cha ...

Apply a sub-schema conditionally, based on the property of another file

Is it possible for json-schema to have a conditional sub-schema based on the property value from another file? For example: Jsons: another.json { "honey": "honey" } main.json { "hello": "abc" } Schema { "type": "object", "properties": { ...

Changing the color of a placeholder using Javascript: A step-by-step guide

I've been searching online without any luck so far. I'm attempting to change the placeholder color of a text box using JavaScript, but I'm not sure how to go about it. I already have a color picker that changes colors. If my CSS looks somet ...

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

The privateroute is throwing an error because it cannot access the property state since

I stumbled upon a tutorial online detailing how to construct a customized private route, but alas, I am encountering an error. Upon execution, I am faced with the dreaded message: "Cannot read property 'state' of undefined" on line 12. As someon ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

"Successfully made an Ajax request to the web handler, however, the response did not

Within my ASP.NET project, I have a Generic handler with the following code: public void ProcessRequest ( HttpContext ctx ) { try { ctx.Response.ContentType = "text/json"; var jsonData = new StreamReader(ctx.Request.InputStrea ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Python string manipulation to create a list from text

I've got a bunch of JSON objects that are all smashed together in a single string. jsonString = "[{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2',&ap ...

Why is there a CSS reference failure in Express and how can it be resolved?

Below, you'll find a simple express server I've put together: // check out my basic Express server var express = require("express"); var app = express(); var bodyparser = require("body-parser"); app.use("/public/", express.static("./public/")); ...

Issue: TypeError: Unable to access the 'getBoundingClientRect' property of an undefined value

Is there anyone who can lend me a hand? I encountered an issue: TypeError: Cannot read property 'getBoundingClientRect' of null https://i.stack.imgur.com/Jnfox.png Here is the code snippet I am trying to render: <div className="box&qu ...

Tips for passing dynamic latitude and longitude values to a JavaScript function within an AngularJS framework

I am facing an issue with displaying a dynamic marker on Google Maps. I can show a static lat long marker, but I am struggling to pass dynamic lat long values to the function. How can I pass {{names.lat}}, {{names.longitude}} to the function so that I can ...

Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don& ...

Any tips on how to convert a bincode serialized data into serde_json::Value?

I'm currently working on an IPC implementation where a process serializes a struct using bincode. However, on the receiving end, the process is unaware of the structure it's receiving. I want to achieve something similar to: let parsed: Result&l ...

Unable to modify the state of data in Vue.js

After developing a weather app, I implemented some components with fields in the data section. However, when I changed the value of these fields in the methods section and attempted to access them in another method, I discovered that the old values were be ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

Activate the Air-mode feature in Summernote in addition to the standard toolbar

Is it possible to have both the default toolbar and air-mode toolbar enabled in the Summernote editor? For instance, I would like the user to utilize the default toolbar for general text editing, but have the air-mode toolbar appear when they select a spe ...

Is it true that URL parameters can be found in two distinct locations within this.props in react-router?

<Route path="lookbook" component={Photos} onEnter={onPageEnter}> <Route path=":photoIdentifier" component={PhotoDetailsModal} onEnter={onPageEnter}> </Route> </Route> While in the PhotoDetailsModal, I used console.log to check ...

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...