Custom Javascript for referrer URL in GTM using custom dimension - google-analytics

GA and GTM noob here.
Need to setup a custom Javascript Variable in GTM to check the referrer URL and set up a custom dimension. I would also need to set up a cookie with some specifications.
How do I go about doing this?

For the referrer you do not need a custom variable - referrer is a built-in, you just need to enable it.
If you insist on using a custom JavaScript it would look something like
function() {
return document.referrer;
}
I do not see any advantage over the built-in.
GTM does not usually set cookies, so you need your own function for this. I suggest you use a Custom Javascript to return a function that sets cookies, and use that function in Custom HTML tags.
Variable setCookie (setCookie function from here)
function() {
return setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
}
Then you can use this in a Custom HTML tag
{{setCookie}}("myCookie","myValue",7);

Related

I want to track internal URL that brought the URL to the next page or exit page

I want to track the URL of the current page, then pass it to a URL variable to the next page.
For example
https://www.mywebsite.com
https://www.mywebsite.com/about/?fromsource=https://www.mywebsite.com
https://www.mywebsite.com/about/careers/?fromsource=https://www.mywebsite.com/about
https://www.mywebsite.com/contact/?fromsource=https://www.mywebsite.com/about/careers
So everytime someone moves to the next page, the URL of the previous page is add to a URL variable in the next page.
I'm not sure if this is the right way. I would use Google Analytics API referral data. But you can create the following shortcode:
function get_current_page_link () {
global $wp; //get global wp query
return home_url( $wp->request ); //get the url of the current page
}
add_shortcode('get_current_page_link ', 'get_current_page_link ');
If you want to add the code via PHP code:
About
If you want to use it in your editor you can add url's as such:
https://www.mywebsite.com/about/?fromsource=[get_current_page_link]
The editor in the text mode, it will show up like this:
About
Why not use document.referrer?
So e.g. create a new variable in your web-analytics system and use the following js code to populate it:
function includeReferrer() {
var ref = document.referrer,
loc = document.location.href,
newLoc;
if (loc.includes('?') != -1) {
newLoc = loc + "&fromsource=" + ref;
} else {
newLoc = loc + "?fromsource=" + ref;
}
}
In this case, you are not overwriting the actual URL, but instead create a new string which includes the requested parameter and can be used for any kind of tracking purpose.

How to send a POST request from GTM custom tag template?

I'm developing a simple custom tag template for Google Tag Manager. It's supposed to bind to some events and send event data to our servers as JSON in the body of a POST request.
The sandboxed GTM Javascript runtime provides the sendPixel() API. However, that only provides GET requests.
How one sends a POST request from within this sandboxed runtime?
You can use a combination of the injectScript and copyFromWindow APIs found here Custom Template APIs.
Basically, the workflow goes like this.
Build a simple script that contains a function attached to the window object that sends a normal XHR post request. The script I made and use can be found here: https://storage.googleapis.com/common-scripts/basicMethods.js
Upload that script somewhere publically accessible so you can import it into your template.
Use the injectScript API to add the script to your custom template.
The injectScript API wants you to provide an onSuccess callback function. Within that function, use the copyWindow api to grab the post request function you created in your script and save it as a variable.
You can now use that variable to send a post request the same way you would use a normal JS function.
The script I included above also includes JSON encode and Base64 encode functions which you can use the same way via the copyWindow api.
I hope that helps. If you need some specific code examples for parts I can help.
According to #Ian Mitchell answer - I've made similar solution.
This is the basic code pattern that can be used inside GTM template code section in such as scenario:
const injectScript = require('injectScript');
const callInWindow = require('callInWindow');
const log = require('logToConsole');
const queryPermission = require('queryPermission');
const postScriptUrl = 'https://myPostScriptUrl'; //provide your script url
const endpoint = 'https://myEndpoint'; //provide your endpoint url
//provide your data; data object contains all properties from fields tab of the GTM template
const data = {
sessionId: data.sessionId,
name: data.name,
description: data.description
};
//add appropriate permission to inject script from 'https://myPostScriptUrl' url in GTM template's privileges tab
if (queryPermission('inject_script', postScriptUrl)) {
injectScript(postScriptUrl, onSuccess, data.gtmOnFailure, postScriptUrl);
} else {
log('postScriptUrl: Script load failed due to permissions mismatch.');
data.gtmOnFailure();
}
function onSuccess() {
//add appropriate permission to call `sendData` variable in GTM template's privileges tab
callInWindow('sendData', gtmData, endpoint);
data.gtmOnSuccess();
}
It's important to remember to add all necessary privillages inside GTM template. Appropriate permissions will show automatically in privillages tab after use pertinent options inside code section.
Your script at 'https://myPostScriptUrl' may looks like this:
function sendData(data, endpoint) {
var xhr = new XMLHttpRequest();
var stringifiedData = JSON.stringify(data);
xhr.open('POST', endpoint);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(stringifiedData);
xhr.onload = function () {
if (xhr.status.toString()[0] !== '2') {
console.error(xhr.status + '> ' + xhr.statusText);
}
};
}
It is not strictly necessary to load an external script. While still a workaround, you can also pass a fetch reference into the tag through a "JavaScript Variable" type variable:
Create a GTM variable of type "JavaScript Variable" with the content "fetch", thus referencing "window.fetch"
Add a text field to your Custom Tag, e. g. named "js.fetchReference".
Use data.fetchReference in your Custom Tag's like you normally would use window.fetch
Make sure the tag instance actually references the variable created in step 2 with {{js.fetchReference}}
I jotted this down with screenshots at https://hume.dev/articles/post-request-custom-template/

Display Custom Dashlet to only specific user on site dashboard

I have created one custom Dashlet, and added it to site dashboard.
But now my requirement is that, I want to display that custom only for site manager and i want to hide it for all other users.
Can anyone help me with this? How can hide custom Dashlet for all consumers and collaborators.
Thanks in advance.
In your controller javascript (aka .get.js file) add an extra remote.call to get the groups of the current user like:
var groupResult = remote.call("/api/people/" + stringUtils.urlEncode(user.name) + "?groups=true");
Use the result and eval it, then send it to your freemarker dashlet.
--- Update ---
You can also take a look at the default share-header webscript.
Take a look at the file org\alfresco\share\imports\share-header.lib.js
The snippet:
// Call the repository to see if the user is site manager or not
var userIsSiteManager = false,
userIsMember = false;
json = remote.call("/api/sites/" + page.url.templateArgs.site + "/memberships/" + encodeURIComponent(user.name));
if (json.status == 200)
{
var obj = eval('(' + json + ')');
if (obj)
{
userIsMember = true;
userIsSiteManager = obj.role == "SiteManager";
}
}
siteData = {};
siteData.profile = profile;
siteData.userIsSiteManager = userIsSiteManager;
siteData.userIsMember = userIsMember;
// Store this in the model to allow for repeat calls to the function (and therefore
// prevent multiple REST calls to the Repository)...
// It also needs to be set in the model as the "userIsSiteManager" is required by the template...
model.siteData = siteData;
so use this in an if statement in freemarker

Getting QueryString for Model in ASP.NET MVC4

I have a simple form based on a model.
One of the features I have to support is the ability to create a url of the current paraments of the model. For example:
Form Begin
Model.Name
Model.Age
Form End
Then in javascript some how get:
http://Site/Controller/Action?Name=Bill&Age=45
Is there a helper that will take the current state and gen a Url?
The reason is that I need to be able to open a new window with the values of the model while leaving the form and page as is.
You should be able to do something like this in your javascript
var url = "#Html.Action("Action", "Controller", new { Name = Model.Name, Age = Model.Age})";
window.open(url);
Use window.location and then window.open to open it in a new window/page/tab.
For example:
var myURL = window.location.href; and then use window.open(myURL)
AFAIK, there isn't a way to get what you are asking (nice idea though). I upvoted NKD because of the second part of your question which was on how to open the browser in a new window (perhaps you already knew how to do this).
you would need to use the JQuery/Javascript way of obtaining the values you desire. Alternatively you could make a quick client helper where you give it the key name you are after, it would find it and give it back to you i.e:
function GetValueFromForm(key)
{
return $('#' + key).val();
}
then you call it:
var url = '/SomeAction?name=' + GetValueFromForm('Name') + '&age=' + GetValueFromForm('Age');
Alternatively, if the data is NOT changing then just use the Model values in your javascript:
var url = '/SomeAction?name=' + #Model.Name + '&age=' + #Model.Age;

Query strip is removed from open graph url

In relation to this question: Dynamic generation of Facebook Open Graph meta tags
I have followed these instructions but the api seems to remove my query string so that the url passed into the aggregation contains none of my dynamic information. If I enter the url with the query string into the debugger it doesn't remove it and works fine. I can confirm my og:url meta tag does also contain the same query string not just the base url. What am I doing wrong?
I was having a similar issue and solved it like this:
So assuming you're doing your post request like it shows in the tutorial, youre Javascript probably looks something like this:
function postNewAction()
{
passString = '&object=http://yoursite.com/appnamespace/object.php';
FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post',
function(response) {
if (!response || response.error) {
alert(response.error.message);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
}
);
}
And since you say you want to generate meta tags dynamically, you're probably adding a parameter to the url (passString) there like so:
passString = '&object=http://yoursite.com/appnamespace/object.php?user=' + someuser;
This is wrong.
What you need to do is to make the url a 'pretty url' and use htaccess to decipher it. So:
passString = '&object=http://yoursite.com/appnamespace/object/someuser';
Then your htaccess file will tell your site that that url actually equates to
http://yoursite.com/appnamespace/object/object.php?user=someuser
Then you can use GET to store the user parameter with php and insert it however you like into your meta tags.
In case youre wondering, in the og:url meta tag's content will be:
$url = 'http://yoursite.com/appnamespace/object/object.php?user=' . $_GET[$user];
Does that help?

Resources