Google Analytics custom variables not showing on reports - variables

I "inherited" this code that is using Google Analytics to track errors using custom variables but they are not showing up on the Google Analytics website. Unfortunately the guy who implemented this no longer works here and no one else knows how it works or can even tell me if these custom variables used to work. I have been reading the documentation and examples on this site and it appears he has it correct. Here is the code minus the account number:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXXX-1']);
_gaq.push(['_setCustomVar', 1, 'ErrorCode', 'BadPassword-05', 3]);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
This code is in the tags before any other javascript. When I go to the Google Analytics site I can see 18,000 visits and it shows me all of the URL information but when I go to Audience->Custom->Custom Variables it doesn't show anything and says there is "no data for this view". From what I understand from the documentation and my web searches that this is where the data should be. Can anyone give me advice on how this works or based on the code if the previous developer even coded it correctly?

This code stores a Custom Variable on the "page" scope ('3' as the last value), and the current GUI, there is no standard report showing page level custom variable reports.
You need to build a Custom Report (table format), with Custom Var value and Page.
This should show you the collected data.

Related

How to read values from a view to insert in ratingValue and ratingCount in my web in order to be recognized by Google Structured data testing tool?

I was using an external service to get Aggregate Rating in my recipes blog, but dis service disappeared so I decided to build one myself. First of all, this is my first experience with cloud data and JavaScript programming so please, be paciente with me :-).
I'm doing my experiments in this duplicate of my blog: https://jleavalc.blogspot.com/
by now it works as I planned, letting one to vote and storing results in a oracle table, making it possible to retrieve results from a view of this table to get ratingCount and ratingValue values, as anyone can see in that link...
But at the end, despite you can see the stars, despite you can vote and get result stored, showing voting results, Structured data testing tool don't see tag values, so all work is useless.
I think I'm getting close to the problem, but not getting close to the solution. I have the impression that the cause of my problems is the asynchrony of the execution of the script that brings the data from the table, while the function is executed, the browser continues to render the page and it doesn't arrive in time to write those values ​​before the google tool can read them, so they appear empty to it.
I have tried everything including labels and variables in GTM with the same result. The latest version of the code, from this morning is installed right before the "/head" tag and it looks like this:
<script style='text/javascript'>
var myPostId = "<data:widgets.Blog.first.posts.first.id/>";
// <![CDATA[
var micuenta = 0;
var nota = 0;
getText("https://ge4e65cc87f573d-XXXXXXXXXXXX.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q={\"receta\":{\"$eq\":\"" + myPostId + "\"}}");
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
let datos = JSON.parse(y);
nota = datos.items[0].media;
micuenta = datos.items[0].votos;
};
// This version gives the same result and is interchangeable with the previous one. I keep it commented so as not to forget it:
// var settings = {
// "url": "https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q={\"receta\":{\"$eq\":\"" + myPostId + "\"}}",
// "method": "GET",
// "timeout": 0,
// "async": false,
// };
// $.ajax(settings).done(function (response) {
// if (response.items.length != 0) {
// micuenta = response.items[0].votos;
// nota = response.items[0].media;
// }
// });
</script>
The key is, I think, getting this call to execute before Google's tool finishes rendering the Blogger post page.
The URL that I invoke to get the data calls an oracle view that returns a single row with the corresponding data from the recipe, placing this call:
recipe
In the browser the result is the following:
{"items":[{"receta":"5086941171011962392","media":4.5,"votos":12}],"hasMore":false,"limit":25,"offset":0,"count":1,"links":[{"rel":"self","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"},{"rel":"edit","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"},{"rel":"describedby","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/metadata-catalog/notas/"},{"rel":"first","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"}]}
And I just need to take the median and votes values ​​to create the RatingCount and RatingValue labels
Can anyone offer me an idea that solves this little problem? :-)

Changing script on website

I was recently asked to change a script that is on this shopify website but I am unable to find it in either the backend settings or the actual code for the template. Could someone please point me in the right direction on how to change the code for this script? The pixel values are wrong here and it's causing SEO issues:
<script>
//<![CDATA[
(function() {
function asyncLoad() {
var urls = ["\/\/productreviews.shopifycdn.com\/assets\/v4\/spr.js?shop=myshop.myshopify.com","\/\/www.beetailer.com\/javascripts\/beecart.js?shop=myshop.myshopify.com","https:\/\/media.conversio.com\/scripts\/shopify.js?shop=myshop.myshopify.com","https:\/\/s3.amazonaws.com\/lastsecondcoupon\/js\/freeshippingbar.js?shop=myshop.myshopify.com","\/\/facebook.shopifycdn.com\/tracking_pixels\/123.js?shop=myshop.myshopify.com","\/\/facebook.shopifycdn.com\/conversion_pixels\/123.js?shop=myshop.myshopify.com","\/\/notifyapp.io\/js\/1463319629\/loader.js?shop=myshop.myshopify.com","https:\/\/embed.tawk.to\/widget-script\/58065fec304e8e75855e4cce\/default.js?shop=myshop.myshopify.com","https:\/\/www.affiliatly.com\/shopify\/shopify.js?affiliatly_code=AF-10200\u0026shop=myshop.myshopify.com"];
for (var i = 0; i < urls.length; i++) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = urls[i];
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
}
window.attachEvent ? window.attachEvent('onload', asyncLoad) : window.addEventListener('load', asyncLoad, false);
})();
//]]>
</script>
This code is included by Shopify as a part of the {{ content_for_header }} Liquid variable in the layout files (e.g. theme.liquid.)
The JavaScript files would be ScriptTag scripts that have been added to the store by Shopify apps that you have installed. For example https://productreviews.shopifycdn.com/assets/v4/spr.js belongs to the Product Reviews app.
These scripts are hosted by the app developers so you won't be able to edit them directly. You can remove a ScriptTag script by uninstalling the Shopify app that placed it there.
It looks like the function above is loading the java script (.js files) dynamically in the code and adding the script to the domain:
var urls = ["\/\/productreviews.shopifycdn.com\/asse....
You would need to download the .js files (url are listed in the code), modify them, and change the path so that the above function can load them from a local path.
Following array is URL to all the JS scripts... Each of the item in this array is loaded after page loads.
var urls = ["\/\/productreviews.shopifycdn.com\/assets\/v4\/spr.js?shop=myshop.myshopify.com","\/\/www.beetailer.com\/javascripts\/beecart.js?shop=myshop.myshopify.com","https:\/\/media.conversio.com\/scripts\/shopify.js?shop=myshop.myshopify.com","https:\/\/s3.amazonaws.com\/lastsecondcoupon\/js\/freeshippingbar.js?shop=myshop.myshopify.com","\/\/facebook.shopifycdn.com\/tracking_pixels\/123.js?shop=myshop.myshopify.com","\/\/facebook.shopifycdn.com\/conversion_pixels\/123.js?shop=myshop.myshopify.com","\/\/notifyapp.io\/js\/1463319629\/loader.js?shop=myshop.myshopify.com","https:\/\/embed.tawk.to\/widget-script\/58065fec304e8e75855e4cce\/default.js?shop=myshop.myshopify.com","https:\/\/www.affiliatly.com\/shopify\/shopify.js?affiliatly_code=AF-10200\u0026shop=myshop.myshopify.com"];

Access Not Configured. The API (Drive API) is not enabled for your project. Please use the Google Developers Console to update your configuration

I got a bit of a problem.
i created a googlesheet and included a script, like this, to send it as a pdf to my email address:
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Custom Menu')
.addItem('Send summary', 'menuItem1')
.addSeparator()
.addItem('Send summary&Week', 'menuItem2')
.addToUi();
}
function menuItem1() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var subject = source.getSheets()[9].getRange('G1').getValue(); //cell for subject in sheet
var body = source.getSheets()[9].getRange('F1').getValue();
var sheetNumSummary = 9; // first sheet(tab) is zero, second sheet is 1, etc..
var source = SpreadsheetApp.getActiveSpreadsheet();
var thema = source.getSheets()[9].getRange('f3').getValue(); //
var mailTo = ('youremailaddress#here.com'); //source.getSheets() [0].getRange('D1').getValue(); // 'D1' cell which consists an emailaddress.
var name = source.getSheets()[9].getRange('G1').getValue(); // Name of Attachement
var sheets = source.getSheets();
sheets.forEach(function (s, i) {
if (i !== sheetNumSummary) s.hideSheet();
});
var url = Drive.Files.get(source.getId())
.exportLinks['application/pdf'];
url = url + '&size=letter' + //paper size
'&portrait=false' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional
'&gridlines=false' + //false = hide gridlines
'&fzr=false'; //do not repeat row headers (frozen rows) on each page
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
now comes the weird thing. I'm able to use it with the Google sheet i used it with, but if i do a copy of it and use the script from the menue i get the message:
Access Not Configured. The API (Drive API) is not enabled for your project. Please use the Google Developers Console to update your configuration.
I checked everything in the admin and developer console, but couldn't find anything. I also activate:
Two-legged OAuth access control Allow access to all APIs
The key and secret above are able to access any user's data for all Google Data APIs. Learn more
If i leave the copy of the 1st sheet and deactivate the API access, the 1st sheet (the origin) doesn't work anymore with the script and i get the above alert message. I have to delete the copy, reactivate the API access to make it work again. So, somehow i guess, the copy is working with the a script that only allows to work with one Project Sheet and not with the copy of that sheet. Is there somehow a way to make it work? Or, how can i add/attach the script to the copy. I used this script:
function getSpreadsheetKey() {
return SpreadsheetApp.getActiveSpreadsheet().getId();
};
and saw that it gives me the google key from the original sheet. that might be the reason why i cant use the script with the copy of the google sheet. But i still don't know how wire it correctly.
This message [(403) Access Not Configured] means that when you set up your Google Drive Access, you missed out "Activate the Drive API". You did not configure the Drive API to enabled in your Google account.
To Activate the Drive API, go to Developers Console and Enable the Google Drive API.
Regarding 'Two -legged OAuth access control' it is not necessary to activate. As stated in the document: to bypass any access control checks in the Google Data API when using the domain key.
You have to Set up API access credentials [OAuth].
Here's a link to enable Drive API: https://developers.google.com/drive/v3/web/enable-sdk
For Two-legged OAuth access control document, here's the link: https://support.google.com/a/answer/162105?hl=en
I just had this problem and it solved it self automatically.
It looks like there is some delay in allowing the API to being used (after it being enabled)
For reference I had enabled the API and setup the two stage OAuth.
Basically what happened was that I had a unit test to validate the access and:
the test failed
googled the error code
saw this SO thread
spent some time trying to figure out what was wrong
run the test again (and it passed)

What is the correct syntax for adding a custom cookie in Google Analytics?

Google's own site seems to provide conflicting documentation.
I've found at least 4 variations for adding A custom cookie to GA.
http://www.google.com/support/forum/p/Google%20Analytics/thread?tid=6a452bd09455721a&hl=en
http://code.google.com/apis/analytics/docs/gaJS/gaJSApiBasicConfiguration.html
http://www.google.com/support/forum/p/Google%20Analytics/thread?tid=4362f4d46e6e723a&hl=en
http://analytics.blogspot.com/2009/07/segment-your-traffic-with-user-defined.html
Here is the code I currently have embedded in my company's sharepoint site. I'm beginning to think that this will not work, and that I will have to create an "employee.html" page on my public webserver that I will have to request all employees load once to generate the cookie on their PC's. My secondary question, is after I setup a employee.html page as the example http://analytics.blogspot.com/2009/07/segment-your-traffic-with-user-defined.html here describes, how do I keep all the external traffic from accessing that same page?
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-20842347-1']);
_gaq.push(['_setCustomVar',1,'visitor-type','employee']);
_gaq.push(['_setDomainName', '.sc-pa.com']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</HEAD>
None of those links talk about setting a custom cookie. Also, it seems to me that you aren't really needing to set a custom cookie. It looks like you are just wanting to be able to segment your traffic into different buckets.
You can do this many different ways, one of which you have in your code example: you can set a custom variable with different values, depending on the type of user.
So it would set the same cookie, etc.. and you pass different values in this line of code
_gaq.push(['_setCustomVar',1,'visitor-type','employee']);
Then in your reports you can setup filters based off of custom variable 1, or look at the custom variable reports directory, or use custom variable 1 as a metric in your reports.

How do I get data from a background page to the content script in google chrome extensions

I've been trying to send data from my background page to a content script in my chrome extension. i can't seem to get it to work. I've read a few posts online but they're not really clear and seem quite high level. I've got managed to get the oauth working using the Oauth contacts example on the Chrome samples. The authentication works, i can get the data and display it in an html page by opening a new tab.
I want to send this data to a content script.
i'm having a lot of trouble with this and would really appreciate if someone could outline the explicit steps you need to follow to send data from a bg page to a content script or even better some code. Any takers?
the code for my background page is below (i've excluded the oauth paramaeters and other )
` function onContacts(text, xhr) {
contacts = [];
var data = JSON.parse(text);
var realdata = data.contacts;
for (var i = 0, person; person = realdata.person[i]; i++) {
var contact = {
'name' : person['name'],
'emails' : person['email']
};
contacts.push(contact); //this array "contacts" is read by the
contacts.html page when opened in a new tab
}
chrome.tabs.create({ 'url' : 'contacts.html'}); sending data to new tab
//chrome.tabs.executeScript(null,{file: "contentscript.js"});
may be this may work?
};
function getContacts() {
oauth.authorize(function() {
console.log("on authorize");
setIcon();
var url = "http://mydataurl/";
oauth.sendSignedRequest(url, onContacts);
});
};
chrome.browserAction.onClicked.addListener(getContacts);`
As i'm not quite sure how to get the data into the content script i wont bother posting the multiple versions of my failed content scripts. if I could just get a sample on how to request the "contacts" array from my content script, and how to send the data from the bg page, that would be great!
You have two options getting the data into the content script:
Using Tab API:
http://code.google.com/chrome/extensions/tabs.html#method-executeScript
Using Messaging:
http://code.google.com/chrome/extensions/messaging.html
Using Tab API
I usually use this approach when my extension will just be used once in a while, for example, setting the image as my desktop wallpaper. People don't set a wallpaper every second, or every minute. They usually do it once a week or even day. So I just inject a content script to that page. It is pretty easy to do so, you can either do it by file or code as explained in the documentation:
chrome.tabs.executeScript(tab.id, {file: 'inject_this.js'}, function() {
console.log('Successfully injected script into the page');
});
Using Messaging
If you are constantly need information from your websites, it would be better to use messaging. There are two types of messaging, Long-lived and Single-requests. Your content script (that you define in the manifest) can listen for extension requests:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == 'ping')
sendResponse({ data: 'pong' });
else
sendResponse({});
});
And your background page could send a message to that content script through messaging. As shown below, it will get the currently selected tab and send a request to that page.
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: 'ping'}, function(response) {
console.log(response.data);
});
});
Depends on your extension which method to use. I have used both. For an extension that will be used like every second, every time, I use Messaging (Long-Lived). For an extension that will not be used every time, then you don't need the content script in every single page, you can just use the Tab API executeScript because it will just inject a content script whenever you need to.
Hope that helps! Do a search on Stackoverflow, there are many answers to content scripts and background pages.
To follow on Mohamed's point.
If you want to pass data from the background script to the content script at initialisation, you can generate another simple script that contains only JSON and execute it beforehand.
Is that what you are looking for?
Otherwise, you will need to use the message passing interface
In the background page:
// Subscribe to onVisited event, so that injectSite() is called once at every pageload.
chrome.history.onVisited.addListener(injectSite);
function injectSite(data) {
// get custom configuration for this URL in the background page.
var site_conf = getSiteConfiguration(data.url);
if (site_conf)
{
chrome.tabs.executeScript({ code: 'PARAMS = ' + JSON.stringify(site_conf) + ';' });
chrome.tabs.executeScript({ file: 'site_injection.js' });
}
}
In the content script page (site_injection.js)
// read config directly from background
console.log(PARAM.whatever);
I thought I'd update this answer for current and future readers.
According to the Chrome API, chrome.extension.onRequest is "[d]eprecated since Chrome 33. Please use runtime.onMessage."
See this tutorial from the Chrome API for code examples on the messaging API.
Also, there are similar (newer) SO posts, such as this one, which are more relevant for the time being.