View Full Version : Get current page URL and use as variable in another function

10-02-2012, 04:17 AM
Total noob to JavaScript: I need to get the current URL of a page and then plug it into a GA custom variable function. Unfortunately i don't really understand JavaScript syntax yet and all of the information I find about how to do this assumes that I do.

What I would like to do is populate the currentPDP portion of the GA snippet with the information being pulled from the variable I made. Do I just need to enclose currentPDP in a $(currentPDP) or something like that? Can anyone help please?

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
var currentPDP = window.location.pathname;
var _gaq =_gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
1, // This custom var is set to slot #1. Required parameter.
'currentPDP', // The name acts as a kind of category for the user activity. Required parameter.
'Yes', // This value of the custom variable. Required parameter.
2 // Sets the scope to session-level. Optional parameter.


10-02-2012, 09:03 AM
No, at the moment your variable is undefined when it is called, I guess, because the document isn’t completely ready yet when the variable is called. Just remove the $(document).ready(function() { and }); or put the location.pathname object right where you call the variable at the moment (you don’t need a variable at all, I suppose).
And I hope you aren’t loading that whole jQuery library just for this one reason?