Get page text using javascript for Google Analytics custom variable - javascript

I want my javascriptcode to capture the text "Personenverzorging" and "Gespecialiseerde voetverzorging" for use within my Google Analytics custom Variables.
This text changes on every page so javascript cannot search on the exact term but it should know where to look within the HTML tags.
<div class="views-field views-field-name">
<span class="field-content">Personenverzorging</span>
</div>
<div class="views-field views-field-name-2">
<span class="field-content">Gespecialiseerde voetverzorging</span>
</div>
This is the Google Analytics code I am going to implement in my website using Google Tagmanager.
_gaq.push(['_setCustomVar',
2, // This custom var is set to slot #2. Required parameter.
'Sub-Section', // The 2nd-level name for your online content categories. Required parameter.
'Fashion', // Sets the value of "Sub-section" to "Fashion" for this particular article. Required parameter.
3 // Sets the scope to page-level. Optional parameter.
]);
Sub-section should be replaced by "Personenverzorging" and Fashion by "gespecialiseerde voetverzorging".
This is the code that I have. But it does not work. Can somebody steer me to the right direction?
Can I use a wildcard since the only unique classes within the page are views-field-name?
var elements = document.getElementsByClassName("views-field-name-*");
var string;
string = "'_setCustomVar',1"
for (var i = 0; i < elements.length; i++) {
string = string + ","+ elements[1].innerText;
string = elements[1].innerText;
document.write(elements[1].innerText);
}
Thanks a lot! I appreciate your help.

If you are using Google Tag Manager, I would use the dataLayer to pass page elements using dataLayer variables. It's going to be much more consistent from page-to-page. It's sort what Google Tag Manager is built to do.
For the example, I'll use 'Sub-section' and 'Fashion' as I do not understand Dutch or the hierarchy of your site, but this should be enough to get you started.
1) Create two new dataLayer variables marcros: one for Sub-section and one for sub-sub-section.
Call them something like subSection and subSubSection, and be sure that they are Version 1 of the dataLayer.
2) Add the dataLayer object to your website. It should look something like this:
<head>
dataLayer = [{
'subSection': 'Personenverzorging',
'subSubSection': 'gespecialiseerde voetverzorging'
}];
</head>
<body>
GTM CONTAINER CODE
</body>
3) Now, propagate the values you want for both 'subSection' and 'subSubSection' using your CMS's global variables. This should happen server-side. So when the page loads, the values will be in there.
4) Once you see that values coming through (you can either look at the source code of the page or type dataLayer in the dev console to inspect the object), you're ready to setup the custom variable.
From what it sounds like, you'll want the CV to trigger on every page. So go back into GTM, and go to your Google Analytics pageview track type, and go to More Settings > Custom Variables > New Custom Variables.
Create your new custom variables, there should be two: one for subSection and one for subSubSection. Pick your slot (1-5), add your name like Sub Section, and then for the value, click the building-block and select the {{subSection}} macro, and then set scope. Publish container, and view data in GA.

Related

Dynamic html- find what variable causes page to update

I'm inspecting a dynamic html webpage. There is an element that looks like this:
<span id="x">3</span>
It's value constantly changes based on some variable. So for example if the variable changes to 10, the text inside the span element will also change to 10 like this:
<span id="x">10</span>
I want to find where this variable is that is causing this change. Where in inspect element can I find this variable and manipulate it?
Try the sources tab of the Dev Tools.
If can't find it in the elements tab, try the sources tab:
For example this is looking at some JavaScript of github.com:
Look for the JavaScript that may be manipulating this element, I have no idea what it could be, but I'd first look for something along the lines of:
var [VARIBALE_NAME] = document.getElementById("x")
Though on many dynamic web pages it can be very difficult to find something like that. This is because many web pages are dynamically created and tend not to be very human-readable.
You should go to script tags in the inspect page and search where it is getting this element. i.e, somewhere in the script there will be something like this;
document.getElementById('x').innerHTML = that-variable-which-you-are-finding; // as the id of the span is x.
In this way you will get the name of the variable. Then in the script tags, search for that variable on other positions and you will get where it is getting updated.

Javascript: Push Mouseflow session ID as a custom dimension to Google Analytics through Google Tag Manager

I want to add the Mouseflow ID as a custom dimension in Analytics. I have my GTM correctly integrated, other tags and triggers work perfectly fine. I'm struggling with the following:
I think I need a custom variable containing javascript that returns the Mouseflow ID. I've used this link as a reference:
https://mouseflow.zendesk.com/hc/en-us/articles/206505015-How-do-I-push-data-into-third-party-tools-
A custom Javscript variable in Google Tag Manager needs a function and return, so I can't use the code on the above website directly. Two of the things I've tried are:
$(window).load(function() {
return mouseflow.getSessionId;
});
And:
function() {
return mouseflow.getSessionId();
}
As you've guessed, I lack Javascript knowledge to implement the code correctly. I've been at it for hours now and thought it was the right time to ask this question here. Closest I've been is getting Object Object in the custom dimension in Analytics, which isn't actually close.
I test the variable by setting the variable as the label of an event, which I configure as a Mouseflow recording in GTM. Only the custom dimension with the variable remains (not set) or Object Object.
Thanks, and if I've missed anything or wasn't clear, please let me know.
Mick
Have you tried looking at this article:
https://mouseflow.zendesk.com/hc/en-us/articles/206505595-Google-Analytics-Integration
Basically, it recommends doing something like this:
if (typeof ga != 'undefined' && typeof mouseflow != 'undefined') {
ga('set', 'dimensionX', mouseflow.getSessionId());
ga('send', 'event', 'Mouseflow', mouseflow.getSessionId(), {'nonInteraction': 1});
}
To use this, you'll need to create a custom dimension in Google Analytics first, and then add the correct dimension name to the code snippet above.
I suspect your problem is that the mouseflow code is loaded at the page bottom. GTM is loaded at the start of the page. Try your second version for a custom js variable, but fire the GA tag only on page load (create a new pageview trigger and set trigger type to window loaded).
As an alternative, set the mouseflow ID in the page source code, push a variable to the datalayer and pick it up via a datalayer variable. Push to the datalayer after your mouseflow code:
$(window).load(function() {
dataLayer.push({"mouseflow_id": mouseflow.getSessionId});
});
then create a new variable of the type dataLayer, set the datalayer key to "mouseflow_id" and use that in your analytics tag.
I've currently set it up as following in Google Tag Manager:
A custom javascript variable containing the following:
function() { return mouseflow.getSessionId(); }
Added a window loaded trigger, made session-scoped dimension in my Google Analytics account. After that I added an event tag for my GA-code, which sets the chosen custom dimension slot with the variable added, using the window loaded trigger.
Worked for my case.

Embed HTML5 / JS Web App with parameters

I have been given a JSON url which returns some data. I need to create a javascript / html5 / css app that will grub this data and return it in a list.
Up to there I'm ok with doing this.
My issue is that I then need to be able to provide a <script></script> which the user can paste in any other website to display the web app.
The script or iframe need to be able to take parameters so it can filter the returned data.
Can anyone guide me in the right direction on instructions on how to do this?
The simplest way is using global variables.
Edit: added a way to "embed" the generated content. I use jQuery in the example, but it can be easily done with any other DOM manipulation library or plain JS.
The final user add an HTML element with a specific id and a <script> tag containing the parameters. We use a div element in the example.
<div id="generated-list"></div>
<script>
// the user defines parameters
var configParameters = {param1: 'some value', param2: ['is', 'array']};
</script>
The final user should paste your code. I have no idea how is your code, so I made this up:
<script>
// The user pastes your script here
// which may be a function accepting the defined parameters
function createList(configParameters) {
// create the necessary elements and append them to the element
// with the right id
// We create an empty ul element in the example
var newList = $('<ul></ul>');
$('#generated-list').append(newList);
}
</script>
Google analytics uses a similar approach

Right implement dataLayer or not?

I need advice. Currently, i have website. There are bookmarks on main page without reload page (onclick). Normally I would not have a problem with it, but i canĀ“t catch relevant data about bookmars like elementID, elementClasses etc (not possible change it).. i attached screen for better idea . Website has many language versions therefore is not possible use Click Text.
I suggest use this on every bookmark:
onclick="dataLayer.push({'event': 'name-of-bookmark'});"
Trigger -> custom event -> fire on: event name=name-of-bookmark
Tag -> UA - Event... -> fire on: bookmark-trigger
Is it right way or you have better solutions?
Am a google analytics expert. When it comes to GTM, the dataLayer is the best guy to trust on events.
Yes the syntax onclick="dataLayer.push({'event': 'name-of-bookmark'});"is correct and you can TRIGGER your event using that event
I always like to avoid inline javascript when I can, I believe it is possible to get what you want without using any dataLayer pushes and it will result in a cleaner implementation. The key is custom dataLayer value macros.
A Simple Example
Let's take the following html example that doesn't have any classes or ids.
<div>
<h2>My First Title</h2>
<img src="picture.png" />
</div>
<div>
<h2>My Second Title</h2>
<img src="picture.png" />
</div>
We want to track when someone clicks on the first link but there doesn't seem to be any default macro we can use to capture the link. Here's where the custom macro comes in
Create a new macro with the following settings:
Macro Name = "elementFirstSiblingInnerHTML"
Type = "DataLayer Variable"
Variable Name = "gtm.element.parentElement.firstElementChild.innerHTML"
You can then create a trigger with the following settings:
Trigger Name = "My First Title Click"
Choose Event = "Click"
Fire On {{elementFirstSiblingInnerHTML}} equal to "My First Title"
Viola, you now have a trigger for when someone clicks on the first link without any classes, ids etc. The macro works by looking at the element's parent's first child's innerHTML which is equal to "My First Title"; setting off the trigger.
This is just one example, but you pretty much have access to the whole DOM via the gtm.element DataLayer variable that gets set on a click. It's just centered around the clicked element.
Create your own dataLayer value macro
Here's an important tip. When developing a macro it's useful to be able to test it out in the web console. However, the console doesn't support the same dot notation as the GTM portal. So in order to develop in the console instead of
gtm.element.parentElement.firstElementChild.innerHTML
you would use (assuming the click event was the 8th event in the dataLayer)
dataLayer[7]["gtm.element"].parentElement.firstElementChild.innerHTML
If you provide me a link to the page you are referring to I could probably come up with a custom macro that would work in your situation. Also, here's a great blog on the subject as well. http://www.simoahava.com/analytics/macro-magic-google-tag-manager/ (item 14 in his list)

html & javascript: How to store data referring to html elements

I'm working on a web application that uses ajax to communicate to the server.
My specific situation is the following:
I have a list of users lined out in the html page. On each of these users i can do the following: change their 'status' or 'remove' them from the account.
What's a good practice for storing information in the page about the following:
the user id
the current status of the user
P.S.: I'm using jQuery.
There is jQuery's data function
$('li').data('userid',uid); // sets the value of userid
uid = $('li').data('userid'); // retrieves the value of userid
official documentation: http://docs.jquery.com/Data
There is a lot of debate as to what is best to use. You can store the data a lot of ways, and they all make someone happy - custom attributes will of course not validate if you use XHTML, and using classes to store one or two bits of data is clumsy at best and only gets worse with the amount of things you want to know. Personally, not only am I not a big fan of XHTML, I am also not much of a validation nazi, so I recommend going with the custom attributes.
There is, however, an option that reconciles custom attributes with standards: data- attributes. As John Resig (the author of jQuery) writes about in his blog, this is a new attribute being introduced in HTML5 that allows you to specify custom data attributes with the data- prefix. So a perfectly valid element might look like this:
<ul>
<li data-userid='5' data-status='active'>Paolo Bergantino</li>
</ul>
This has the upside that while you are still using custom attributes which may be bad if you are using XHTML, your code is going to age very well as this is the way that we will be storing data related to a particular item in the future.
Some further reading is Attributes > Classes: Custom DOM Attributes for Fun and Profit.
Perhaps using custom attributes, so for a user's list element, add attributes for the variables:
<li uid="theuserid" ustatus="thestatus"></li>
The values can then be got with the attr function:
$("li").attr("uid")
And
$("li").attr("ustatus")
Note: The selectors will need to be changed, obviously
Please note that there are differing opinions on the use of custom attributes - however, this should be fine for every major browser. It is also the least complex solution I can think of. It doesn't require jumping to sibling elements to get data, or finding elements nearby, which can all add a small amount of overhead to processing - I try to minimise the amount of extra bloat I add to the DOM when doing such things.
jQuery Data
If you want to store custom data against a jQuery object, use the data function.
$('#myField').data('name', 'Jack');
var name = $('#myField').data('name');
HTML5 data-* Attributes
You can also use the HTML5 data-* attributes, though the APIs for accessing these are only partially supported by the different browsers. Here's some more information about that.
<div data-userid="123" class="user-row">
programmatically:
$('#myElement').attr('data-fruit', 'apple');
// or
document.getElementById('myElement').dataset.fruit = 'apple';
Hidden Fields
If you want to do things the old browser-compatible way and stuff the metadata directly into your html, you can use hidden fields. It's a bit cruder but easy enough to do.
<input type="hidden" name="UserID" value="[userid]" />
You can easily use jQuery selectors to query your list and find html blocks that contain user items that have the relevant hidden fields that match the metadata you are querying for.
In this case, I think custom attributes might be overkill. You can store the user-id in the id-attribute, since there will only be one instance of the user in the list, right? Also, the status of the user could be stored in the class-attribute. In this way, each user could be given different styling in CSS, such as green for active, yellow for a non-activated account, and red for a suspended account.
The code for fetching the status will, however, be a little more complex compared to using a custom attribute (But only if you also want to have multiple classes). On a more positive note, the HTML will validate with this approach whereas it would not with custom attributes.
<ul id="userList">
<li id="uid123" class="active">UserName X</li>
<li id="uid456" class="suspended">Mr. Troll</li>
</ul>
/**
* Simple function for searching (strict) for a value in an array
* #param array arr The array to look in
* #param mixed val The value to look for in arr. Note that the value is looked for using strict comparison
* #return boolean true if val is found in arr, else false
*/
function searchArray(arr, val) {
for(var i = 0, len = arr.length; i < len; i++) {
if(arr[i] === val) {
return true;
}
}
return false;
}
/**
* Gets a known status from a string of class names. Each class name should be separated
* by a space.
* #param string classNames The string to check for a known status
* #return string|false The status if found in classNames, else false
*/
function getStatus(classNames) {
// The different statuses a user can have. Change this into your own!
var statuses = ['active', 'suspended', 'inactive'],
nameArr = classNames.split(" ");
for(var i = 0, nameLen = nameArr.length; i < nameLen; i++) {
// If we find a valid status among the class names, return it
if(searchArray(statuses, nameArr[i])) {
return nameArr[i];
}
}
return false; // We didn't find any known status in classNames
}
var id = $("li").attr("id"); // Fetches the id for the first user
var status = getStatus($("li").attr("class")); // Fetches the status of the first user
The metadata plugin to jquery is your answer.
<html >
<head>
<script src="/js/jquery-1.3.2.js"></script>
<script src="/js/jquery.metadata.js"></script>
</head>
<body>
<ul>
<li type="text" class="{UID:'1',status:'alive'}">Adam</li>
<li type="text" class="{UID:'2',status:'alive'}">Bob</li>
<li type="text" class="{UID:'3',status:'alive'}">Carol</li>
</ul>
<script>
$('li').each(function(){window.console.log($(this).metadata().UID)});
</script>
</body>
</html>
There are various ways of doing it depending on the kind of data you are storing and how much information you are storing in the page in general. It's best to devise a consistent scheme so you can write a simple library call to do the work. For example,
You can store data in the class of a particular element. This may require additional wrapper elements in order to be able to provide an additional class to drive your CSS. This also restricts the storable content format. User ID may well fit into a class attribute.
You can store data in an unused href of a Javascript activated link. This has the additional feature of showing the data in the status bar as part of the URL on rollover. For instance you can store '#userid' or even just 'userid' in the href.
You can store data in additional elements. For instance you can have a nested div with a class that indicates storage which also triggers CSS to take the element out of the display. This is the most general and extensive support you can probably arrange in page.
Rather than a nested div you could also use nested input tags with type="hidden". This is kind of more expected / traditional and doesn't require CSS to take them out of the display. You can use the id attribute to identify these inputs, or you can use the location on the page. For instance, put them inside the link that the user clicks and then just search inside the current link in the onclick handler.
To answer the question of "how to get it into the document in the first place", I suggest a layout similar to this:
<ul id="users">
<li id="someUserId" class="someStatus">Some Username</li>
<li id="someOtherUserId" class="someOtherStatus">Some Username</li>
</ul>
This allows you to easily select a lot of info about your users:
$('#users > li') // all user elements
$('.someStatus') // all users of a particular status
Then in your event handlers it's also easy to get the current status:
$(this).attr('class') //get current status once you have a user element selected.
Another alternative is to dump javascript to the page and simply have it use the jquery data functionality to store the data as soon as the page loads. You'd still need an id on the element in order to find the right one though.

Categories

Resources