XMLHttpRequest() and Google Analytics Tracking - javascript

I have implemented an XMLHttpRequest() call to a standalone html page which simply has an html, title & body tag which Google Analytics Tracking code.
I want to track when someone makes a request to display information (i.e. phone number) to try and understand what portion of people look at my directory versus obtaining a phone number to make a call.
It is very simple code:
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "/registerPhoneClick.htm?id=" + id, false);
xhReq.send(null);
var serverResponse = xhReq.responseText
Yet I cannot see the "hit" in Analytics... Has anyone had this issue? All the analytics tracking code does is call:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-XXXXXXX");
pageTracker._trackPageview();
} catch(err) {}</script>
So realistically, my XmlHTTPRequest() calls an htm file within which a script is execute to make an outbound call to Google Analytics.
Is there any reason why an XmlHTTPRequest() would not execute this?
Does an XmlHTTPRequest() still bring the code to the client before execution?
Help Please

Requesting the file doesn't mean that it's automatically executed. You just get the content of the file back as a string.
For the code to be executed, it would have to be loaded as a page in the browser. You can for example use an iframe to load it.

To those having similar issues, obviously analytics won't track XMLHttpRequest() so to get around it, I found this post: Tracking API: Basic Configuration which explains how to simply log a pageview using javascript.
I simply added the following code to my javascrip:
var pageTracker = _gat._getTracker("UA-XXXXX-XXX");
pageTracker._trackPageview("/home/landingPage");
Much cleaner, easier and simpler than what I was originally trying to do...

Related

Passing Javascript variables in URL

I am trying to pass a javascript variable to a php page via the URL. The code below triggers the php page but it doesn't get the variable. I have written the code using window.location.href and that works fine, the problem is doing it that way it loads the tracker.php page.
Below is my code.
<script type="text/javascript">
var siteId = "VT0013";
</script>
<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId="+ siteId ;>
</script>
PHP Page
$siteId = $_GET["siteId"];
Once I get the siteId I email the result as a test this works fine, except I am not getting the value of siteId. When using this same code with window.location.href it all works fine.
I'm guessing that since this is called tracker.php, you actually just need to hit this URL? If that's the case, consider using the Beacon API.
navigator.sendBeacon('https://example.com/tracker.php' {
siteId: 'VT0013'
});
This results in an HTTP POST request, but that's generally better for this anyway. You won't have to worry about caching. Also, the Beacon API will still work even if the request hasn't finished and the page is being unloaded.
If you actually do want to dynamically loads JavaScript instead, a current way to do that is to use import().
const siteId = 'VT0013';
await import (`https://example.com/tracker.php?siteId${encodeURIComponent(siteId)}`);
Finally, if you need to dynamically load this JavaScript and that script needs to run in the context of the rest of the page (i.e., not a module) then the best thing to do is inject a new script tag: https://stackoverflow.com/a/8578840/362536
No matter what you do, make sure you're escaping the data used in your URLs and in your HTML.
You can just do a quick XHR request if you want older browser support without polyfills:
var siteId = 'VT0013';
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', 'http://www.domainame.com/tracker.php?siteId=' + encodeURIComponent(siteId));
xhr.send();
This is just an alternate solution, #Brad's answer should be accepted.
You need to use document.write to write any HTML that contains JavaScript variables:
<script type="text/javascript">
var siteId = "VT0013";
document.write('<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId='+encodeURIComponent(siteId)+'">
<\/script>')
</script>
This is the equivalent of writing
<script type="text/javascript">
var siteId = "VT0013";
</script>
<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId=VT0013"></script>
Edited to properly escape JavaScript variable.
Please note that it is not advisable to use document.write to load scripts from a third-party domain because Google Chrome might choose not to load the script if the connection is too slow. See https://developers.google.com/web/updates/2016/08/removing-document-write.
If the script can be loaded asynchronously, I recommend this method instead because it will not slow down the HTML parser:
<script>
var siteId = "VT0013";
(function(d, s){
s = d.createElement("script");
s.src = "http://www.domainame.com/tracker.php?siteId="+encodeURIComponent(siteId);
d.getElementsByTagName("head")[0].appendChild(s);
})(document)
</script>

JavaScript function is loaded via Ajax but not executed?

I have different websites that have the same data protection. So that the text does not have to be changed every time on all pages, there is a file on another server that is integrated via Ajax.
There is a part where you can set an opt-out and the domain of the respective page must be stored there.
I don't want to get tracked!
<script type="text/javascript">
document.getElementById("setOptOut").addEventListener('click', function(e) {
e.preventDefault();
var redirect = 'https://' + window.location.hostname + '/privacy';
var url = encodeURIComponent(redirect);
location.href = url;
});
</script>
The code above which is in an HTML file is loaded successfull via Ajax into the document of the web page, but when I click on the link the function is not executed.
If I call the HTML file directly on the server, everything works as expected. Why doesn't it work with Ajax?
Found this good example: https://subinsb.com/how-to-execute-javascript-in-ajax-response/
I used eval() to make the code in the AJAX response execute.

Dynamically insert and execute a script resource

Hope I can explain this properly. We are currently inserting this external JS in our HTML:
<script src="https://NotOurDomain.com/SomeScript.js"></script>
The code in this script resource is something like this:
var callbackUrl = encodeURIComponent(window.location.href);
var token = encodeURIComponent('eidoasjdiojancoxjnegkjasd');
var url = 'https://NotOurDomain.com/path?token=' + token + '&callbackUrl=' + callbackUrl;
document.open();
document.write('<iframe src="' + url + '"></iframe>');
document.close();
This all works fine, but now I need to insert this dynamically. Problem is, I can't just copy the code in this script resource because the "token" part changes periodically.
How can I get this to work? Is it possible to load https://NotOurDomain.com/SomeScript.js as a string and parse out the token so that I could create and insert an iframe with the correct URL? Or is there a simpler way of doing this?
This obviously does not work because a script include will only execute on load:
jQuery('#someDiv').append('<script src="https://NotOurDomain.com/SomeScript.js"></script>');
But is there some way to get it to "eval" after inserting?

Print external javascript file contents on page

I have a js file that stores google analytics data. I am hard coding them on all the pages. For a change in one value, I have to make changes on 1000+ pages, as I am hard coding it.
Below is my google code.
//Google Tracking Code Part 01
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
//Google Tracking Code Part 02
try {
var pageTracker = _gat._getTracker("xx-12345678-12");
pageTracker._trackPageview();
} catch (err) {
}
So I have created an external JavaScript file called googleAnalytics.js, where the above code would exist, so that when I make a change, it automatically gets reflected on all the pages.
Is there a javascript code that prints this external file codes on all the pages (i.e the source and not text) by reading the contents from the external file ??

Can't figure out how to do XMLHttpRequest to google app engine

I'm trying to do a simple POST from a javascript (google chrome extension) to my google app
I can see that the HTTP POST is indeed sent to the GAE server, but I can't figure how to transfer a simple text string, and use it in the google app.
The goal: send a string from the javascript with xmlhttpRequest, show this string on google-app webpage.
Here's the code of the javascript:
function onRequest(request, sender, sendResponse) {
var url = request;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myapp.appspot.com");
xhr.send(url);
// Return nothing to let the connection be cleaned up.
sendResponse({});
};
Here's how I deal with the post in the server side:
def post(self):
url1 = str(self.request.get('url1'))
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write('<p>URL is: %s</p>' % url1)
When I look at the POST response I see
<p>URL is: </p>
where is the var url that was sent?
I got it to work, in a different way. Instead of XMLHttpRequest, I used jquery:
$.post("http://myapp.appspot.com", { url1: request});
and it worked :)
BTW, I also discovered that if you want the chrome extension's html to use jquery, you need to do
<script src="jquery-1.5.1.js"></script>
<script> your code here </script>
(I'm sure it's basic for you guys but fresh for me :)
The content you include with xhr.send() will be in self.request.body, if it's not specified in CGI format. For your simple test, you might also try xhr.send("url1=" + request).

Categories

Resources