Pregunta

I am developing Analytics application and I need a way to identify each user device uniquely. For this, the approach I am following is creating a "cookie" from a server side. All page clicks and tracking will be updated to server using Ajax requests.

My problem is, I have my analytics in xyz.com. Abc.com and 123.com are the applications which installs my plugin(javascript) code. On the first visit, I am creating a cookie "sha1" to identify each user/device uniquely, on each consecutive requests, I need to check in server whether cookie "sha1" exists, on based on that should have to take necessary action. Since I am making Ajax calls to the server and since it is a cross domain request, no cookies are added to the request. I have looked at various options available to include cookies to request like setting "withCredentials=true", "crossDomain=true", but with no success.

I want the solution using Pure Javascript and would be really grateful if any one help me out. Also I am open to change my approach, if any feasible and easy to implement solution is recommended.

¿Fue útil?

Solución

Here is an XMLHttpRequest() example that i have used for CORS with cookie credentials successfully in Chrome, FF 3.5+, Safari 4+, IE10+. If this does not work, it is probably something wrong with server configuration or browser compatibility.

// GET request
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = 'application/json';
xhr.processData = false;
xhr.contentType = false;
xhr.onload = function() {
    // Successful request
    if (xhr.status == 200) {
        success(xhr.response);
    }
};
xhr.onerror = function() {
    // Crossdomain request denied
    if (xhr.status === 0) {
        corsFailed(xhr.response);
    }
};
xhr.crossDomain = true;
xhr.withCredentials = true;
xhr.send();

I know that safari and IE10+ require the user to allow third party cookies in their browser preferences. I don't think there is any way around this without using custom headers in place of cookies and setting the Access-Control-Allow-Headers on the server to include the custom headers. Also I believe you need Access-Control-Allow-Headers: "Content-Type".

To go back as far as IE8/9, you would need to implement a fallback to XDomainRequest(), but those do not support cookie credentials.

The processData and contentType flags may only be necessary for POST requests. I use FormData() objects when doing POSTs, not JSON.

Otros consejos

It can't be done in js, you need to modify the headers sent from the server:

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

How to add those headers, depend on which software are you using to serve pages.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top