Using Google Analytics Tracker Client ID (cid) - javascript

I'm planning to use Google Analytics Measurement Protocol. I'm currently planning to capture the Client ID (cid) by including it as a URL parameter on some Ajax requests.
I've found that I can expose the Client ID value like this:
var ga_cid;
ga(function(tracker) {
ga_cid = tracker.get('clientId');
});
I'm concerned that this route is poor form as it's polluting the global namespace. However, I've been unable to unearth a more elegant (best practice) solution.
What is the "right" way? Am I overthinking this?

Yes you may be right on this. Its instead better not to get the Client ID from the Cookie as the official documentation recommends. You can do something like below:
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
There are more options mentioned on this page on how to retrieve it based on how your page is setup.

I ended up making a cookie and referencing it from PHP instead of a global JavaScript variable that I'd have to pass when making AJAX calls.
// put the Google Analytics Client ID into a cookie, so that it will be available to PHP
ga(function(tracker) {
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
document.cookie = 'ga_cid=' + tracker.get('clientId') + '; expires=' + date.toUTCString() + '; path=/';
});
Then in PHP:
$ga_cid = filter_input(INPUT_COOKIE, 'ga_cid');

Related

Yii 2 Not Reading a Cookie Set From Javascript

Is there a way to get the value of a cookie set by Javascript inside the Yii 2 framework?
Using this code
if(Yii::$app->getRequest()->getCookies()->has('HELLO'))
{
die("YES COOKIE");
}
else
{
die("NO COOKIE");
}
And I am seeing the HELLO cookie has been set when I inspect. However, the code is returning NO COOKIE.
The cookie was set with Javascript like so
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
cookies you set in javascript won't pass yii validation when you attempt to access them.
the whole purpose of the validation is to ensure that cookies that yii reads and writes are not tampered with.
i dont know your exact use case, but if you need a client action to set cookie data, i'd prefer to set it via an ajax request.
if it's not something sensitive (like getting a tab state or smth), use the $_COOKIE global to access it.
or, the nuclear option, disable cookie validation altogether in application config
docs could help you out here

How to modify / add to Cookie in JMeter?

I'm very new to JMeter and need your help on how to modify a cookie.
Here is the scenario:
I'm testing an assessment/test taking website that offers multiple answers to questions. When a user makes his selections and hits the submit button, the JavaScript in the page appends his answers (e.g., "Answers = BBAACDA...") to the cookie and makes the next GET request (instead of a POST request!).
Since, JMeter does not execute JavaScript (as popularly mentioned in its manual - it's not a browser), it cannot append the answers to the cookie. As a result, my test plan fails to recognize user interaction.
How can I add/append/modify a dynamic cookie? Thanks in advance!
--Ishti
Use a Beanshell pre-processor or better a Jsr223 Pre-Processor with groovy and use code mentionned here:
http://javaworks.wordpress.com/2011/08/05/setting-cookie-in-jmeter/
Code:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
CookieManager manager = sampler.getCookieManager();
Cookie cookie = new Cookie("<NAME>","<VALUE>","<HOST>","/",false,0);
manager.add(cookie);
I had to implement some changes in the code that worked for me:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
Cookie cookie = new Cookie("<NAME>","<VALUE>","<DOMAIN>","<PATH>",false,0, true, true, 0);
manager.add(cookie);
Following the definition in http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/Cookie.html
It is possible to modify or add a cookie manually in a groovy pre-processor script in the same way as https://stackoverflow.com/a/38505077/5747304.
Here's how to find and edit a cookie by browsing all cookies in the cookie manager:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
log.info("#########################################################################");
// cookie manager
CookieManager manager = ctx.getCurrentSampler().getCookieManager();
def NbOfCookies = manager.getCookieCount();
for (def i = 0; i < NbOfCookies; i++) {
log.info("Cookie n° " + (i+1) + ": " + manager.get(i).getName() + ": " + manager.get(i).getValue());
if (manager.get(i).getName() == "Cookie_name_to_find") {
log.info("MAJ of Cookie_name_to_find");
manager.get(i).setValue("New_cookie_value");
log.info("-> " + manager.get(i).getName() + ": " + manager.get(i).getValue());
}
}
log.info("#########################################################################");
Here is the list of cookie manager methods like add or delete ...: http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/CookieManager.html.
Here is the list of cookie methods to modify more properties like the domain, its expiration date ...: http://jmeter.apache.org/api/org/apache/jmeter/protocol/http/control/Cookie .html
It should be known that according to the standart chosen in the cookie manager, the manually modified values can still be modified by the manager before the request so you have to be careful.

How to store this data in cookies?

Let's say i have some textboxes/textareas of which the values have to be stored. The values have to be stored on key press, so that no data is lost when the user closes the page too early. Here's my current code (using cookies):
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = '; expires=' + date.toGMTString();
} else var expires = '';
document.cookie = name + '=' + value + expires + '; path=/';
}
$('input').keyup(function () {
var $this = $(this);
createCookie($this.attr('name'), $this.val(), 1);
});
jsFiddle
This works great.
With just 4 textboxes i see no problems but imagine having 50+ textboxes or textareas (not accounting usability/user experience). Will this cause any problems?
I'm open to any suggestions/alternatives
I'd opt for using local storage (see http://www.w3schools.com/html/html5_webstorage.asp), seems more scalable than setting a cookie for each text input.
Also, you mention that the values must be set with each keystroke, why not instead keep the value of the current input in memory, and bind a function which commits the value both to the blur event of the input, and also use setTimeout to impose, say, a 1 second delay on saving the value, queuing these timeouts in an array, and clearing outstanding ones on each keyup event, that way you're only writing to the local storage when the user pauses typing, not with every keystroke.
As Jamie suggested local storage is a really good approach, cookies could be used as a fallback if Local Storage is not supported.
On the snippet you have provided you have binded the cookie rewrite process in the keyup event, in order to avoid any data loss.
I have implemented a more neat solution , when the user unloads the window I have tried to serialise the form data and store it.
//save data generic function
function saveData() {
var dataObj = JSON.stringify($("input,textarea").serializeObject());
if (!Modernizr.localstorage) {
saveToLocalStorage(dataObj);
} else {
createCookie("jsonobj", dataObj, 1);
}
}
Modernizr is used to detect when local storage is available. Furthermore , I have found that using separate cookies for each field is an overkill, I have used a single JSON string instead.
Full jsFiddele example: http://jsfiddle.net/ARUM9/5/
Further reading:
Local storage :Storing Objects in HTML5 localStorage
Local storage browser support: http://caniuse.com/#search=localstorage
Using JSON serialisation : Serializing to JSON in jQuery
Modernizr documentation: http://modernizr.com/docs/
Use jquery-storage for saving the values https://github.com/julien-maurel/jQuery-Storage-API/blob/master/README.md
Its really simple
$.localstorage.set(inputfield, value)
For setting
$.localstorage.get(inputfield)
For retrieving.
Cookies are often abused for this purpose but cookies get sent to the server on every request. So storing a ton of data in cookies is not a good idea.
Localstorage however was designed for this purpose and is a simpe key value storw in the browser.
Please note that it is a html5 feature and will not work in some older browsers
To circumvent this you can use the cookiestorage provided by jquery storage. But then you also need to include the extra dependencies mentionend in the readme.md
Then use it like this:
var store = $.localstoreage || $.cookiestorage:
store.set(...........

How to save cookies [duplicate]

This question already has answers here:
Simple PHP login with cookie
(2 answers)
Closed 9 years ago.
How would I go about having people that say they directly login to my website,
How would I make it to where, Once they login they are actually loged in via cookies?
To say something like this.
"If you would like to actually completely access the website you signup and login, But once you login it saves your cookies, Intill loging out."
At the moment, I have the signup and the login but it's not saving the cookies. :\
<script type="text/javascript">
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
</script>
You can set the cookies as like
setCookie(test_cookie,5);
You can get the cookies as like
getCookie(test_cookie);
Hope it may helps to someone else. . .
You don't need jQuery to read/write cookies. You can use plain javascript. Some good examples are here: http://www.quirksmode.org/js/cookies.html
You can use this jQuery plugin to make getting and setting cookies a little easier:
http://plugins.jquery.com/project/Cookie

Setting timezone on Rails from clientside using javascript

I have a webapp that sets timezone
post_controller.rb
before_filter :set_time_zone
def set_time_zone
Time.zone = user.time_zone
end
Now, instead of getting the time_zone from the user at registration, I was wondering how I'd set the timezone dynamically from the client side and set it in the before_filter.
I was trying to use detect_timezone_rails gem. The gem provides an easy way to access clientside timezone, simply by calling the function like this from js file.
$(document).ready(function(){
$('#your_input_id').set_timezone();
});
Now, the above code automatically sets your hiddenfield input or select input, but I was wondering if you could simply use the function call to save to session and retrieve it from Rails server. I guess when the user first visits the site, the timezone can be set and the session value can be used to set timezone for the rest of the visit. I'd think it'd be possible to use the session value to set timezone in the before filter. Being pretty new to javascript, I'm not sure how to access Rail's encrypted cookie store to set the value. Is this possible? if so, how can I do this?
thanks in advance,
#javascript
function readCookieValue(cookieName)
{
return (result = new RegExp('(?:^|; )' + encodeURIComponent(cookieName) + '=([^;]*)').exec(document.cookie)) ? decodeURIComponent(result[1]) : null;
}
$(document).ready(function(){
if(readCookieValue("time_zone") === null) {
$.post('/set_time_zone',
{ 'offset_minutes':(-1 * (new Date()).getTimezoneOffset())});
}
#controller:
def set_time_zone
offset_seconds = params[:offset_minutes].to_i * 60
#time_zone = ActiveSupport::TimeZone[offset_seconds]
#time_zone = ActiveSupport::TimeZone["UTC"] unless #time_zone
if #time_zone
cookies[:time_zone] = #time_zone.name if #time_zone
render :text => "success"
else
render :text => "error"
end
end
We did this somewhat differently. We use the gon gem to set a variable on the Rails side if we want to collect the timezone from JS. Then we have JS code on the client that examines that variable, and if set, does an XHR post to an endpoint (like the OP did) with the timezone string as returned by the jstimezonedetect script, which returns an IANA timezone key. Finally, to convert this to a Rails 3.2.19 timezone name, we did ActiveSupport::TimeZone::MAPPING.invert[iana_key]. It took a few steps to figure this out, hope it helps someone.

Categories