My script tracks clicks on a client’s page and uploads this to my server(let’s call it .http://fancyclickserver23.net)
Now I want the client to put a script on his site and this script will tag the clicks on the page and send the data to .http://fancyclickserver23.net on page leave or maybe even from time to time.
I can’t use Ajax because of cross browser restrictions, ofcourse. So how do I do this?
I’ll give a little hypothetical code to help you understand.
I have a closure tracker which is loaded when the user puts
<script src="http://fancyclickserver23.net/loadtracker.php?client_id=2332"></script>
The code loads the closure tracker=function(){….};
The user needs to create an object of tracker
<script>
track=new tracker();
track.init();
</script>
track.init() basically binds a function that gets the Xpath of the element and stores it in track.clicks . Now i need to have a function track.send() which will send the clicks array as json(I know how to convert it to json) and send it on page close.
How do I do this. Also I have seen some sites use something like:
document.write("<sc"+"ript"+" src='https://fancyclickserver23.net/loadtracker.php?client_id=2332'"+"></scr"+"ipt>";
Why do this instead of a direct script tag? And why not put it in one string if we must use document.write() at all.
So the two questions are:
- How do I send the data asyncronously(or otherwise) on page load?
- What does the above code do?
- I’ve seen Google analytics and Facebook do this, they don’t seem to have any problems. Facebook infact renders the dialog box on screen. How?
Despite the cross-domain security restrictions, you can still use AJAX (XHR) to some extent.
Browser can not trash a cross-domain request just like that. It has to see what the server thinks of it first. It does this by sending the actual request over to the server and receiving the instructions along with the response in HTTP headers. If the
Access-Control-Allow-Originheader doesn’t arrive or doesn’t match the origin domain, browser trashes the response and throws out a security warning in the console.From my personal experience,
Access-Control-Allow-Originheader or not, when site aaa.com sends an AJAX request to site bbb.com the one-way delivery of the data payload to the server happens anyway. It’s just a monologue, but what more do one need for collection of data, right? 😉I, for example, utilize the one-way technique for something similar to yours – I collect JSON reports of unit tests results of my open-source project here. You can spot the security warning in the console, but at that time the report is already stored safely on the server.