According to Google Analytics:
The total combined length of any custom variable name and value may
not exceed 64 bytes. Keep in mind that this is not equivalent to 64
characters. Because names and values are URI encoded when stored, some
characters use more than one byte. For example, = is stored as %3D
rather than = and uses 3 bytes rather than 1. To get a list of URI
encoded values, search the web for URL encoding reference.
I have two questions about that:
- Should an encoded equal sign (=) be included in those 64 bytes?
-
I’ve tried to make a function that makes sure the custom name and value is not too long.
Can it be improved? (Of course it can.)function truncateCustomVarAndSet(index, name, value, scope) { var keyValuePair, encodedPair, lengthOK = false; while (!lengthOK && value.length > 0) { keyValuePair = name + '=' + value; encodedPair = encodeURIComponent(keyValuePair); lengthOK = encodedPair.length <= 64; if (!lengthOK) { value = value.substring(0, value.length - 1); } } _gaq.push(['_setCustomVar', index, name, value, scope]); }
Edit: Now using encodeURIComponent instead of encodeURI.
Edit 2: @yahelc changed gaq to _qac, so I removed gaq from the argument list since it isn’t needed anymore.
I’ve tested pushing custom variables of exactly 64 characters combined, and it looks like 64 is ONLY the encoded bytes of the key and the value, not of any connecting characters.
You should use
encodeURIComponent, because thanencodeURIdoes not encode&,+, and=.Also, don’t forget the underscore in front of
_gaq._gaqneeds to be a global variable, so, no need to pass it through as a parameter.It looks like your general approach works, and avoids the issue of mistakenly cropping the string in the middle of an encoded character (as my previous approach mistakenly did.)
Here’s a slimmed down version of your code (cuts ~220 chars):
Tested with this:
And that records as: