I am figuring out of i can make something like Google analytics script. They work with javascript to capture data and send it to an given URL. But i want it to do without ajax or REST API.
What i found so far:
<script type="text/javascript">
var statsPage = 'http://www.uw-url.be/process.php';
var stats = {
page: location.href,
browser: 'ie',
ip: '127.0.0.1',
referral: 'google.com?search=test'
};
var params = $.param(stats);
alert(statsPage+'?'+params);
</script>
The alert message gives everything i need, but the problem is how can i send those data to statsPage URL? I found a little solution around the web for that but i don't know of it is ok... Maybe there is a better solution to do this, but i don't know... I'm listening to you guys!
$('<img>', {
src: statsPage + '?' + params
}).appendTo('body').remove()
There is something else... If i look to the analytics javascript code this is a total other script. Can anyone explain me how it works?
An example here:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-49578310-1', 'auto');
ga('send', 'pageview');
</script>
The meaning of the whole thing here is that everyone can use this on their website. With AJAX or REST API it is not possible to integrate it simply. Not anyone can work with that.
For my first posted script i make also use of jquery () for that. Analytics script don't.
EDIT
I have build a new code based on the answer from Peter G. I don't need jquery for that. Is this code safe enough to use? I have written a function for the p var:
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
The whole script below:
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
Like you can see, i have hidden the addEventListener here. What is the difference to use this with or without that?
1 Answer 1
Some inspection of the code used by Google Analytics (use an unminifier like http://unminify.com/ ...the code is far too long to reproduce here) shows that most of the code is related to determining WHAT to send, rather than how to send it. Here's the interesting part about how they send it:
// ...
wd = function(a, b, c) {
var d = O.XMLHttpRequest;
if (!d) return !1;
var e = new d;
if (!("withCredentials" in e)) return !1;
e.open("POST", a, !0);
e.withCredentials = !0;
e.setRequestHeader("Content-Type", "text/plain");
e.onreadystatechange = function() {
4 == e.readyState && (c(), e = null)
};
e.send(b);
return !0
},
x = function(a, b, c) {
return O.navigator.sendBeacon ? O.navigator.sendBeacon(a, b) ? (c(), !0) : !1 : !1
},
// ...
O is the window object. They perform an XMLHTTPRequest when the page is loaded and they use the navigator.sendBeacon function when the page is closed. If all you want to do is send your data over the internet, I'd suggest the XMLHTTPRequest method, as navigator.sendBeacon is intended to send data on page close (so the page doesn't lag when closed, you'll see no difference on page load). If all you want to do is send the data as a GET request, you can do the following (although, you should consider refactoring so you can use a POST request instead...).
const req = new XMLHttpRequest();
req.addEventListener('load', /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
Note that you don't actually need the addEventListener callback if you don't care about the result of the call. Read more about XMLHttpRequest() here.
You might also run into CORS issues if the URL you're requesting is different from the one you're on and you use the addEventHandler callbacks. Read more on that on this SO page seeing as it's out of the scope of this question.
9 Comments
params string isn't correct I don't think. I tested it with {lol: 5, la:1} and got 'lol=undefined&la=undefined'. Another thing to be careful of is that in function ca(c,o,n,t,e,t,u) the second t won't do anything. If you use addEventListener it will fire a callback letting you know if the request returns successfully or not. You probably don't need this for analytics.