set page google analytics - javascript

I am trying to force the Page Tracking on my site (see: Link). I am using a TMS, but not Google Tag Manager.
What I am hoping to achieve is prepend the market name to the URI which I can pull out of my site's dataLayer (variable = dataLayer.language and thus the new Page Path: dataLayer.language.substring(0,2)+document.location.pathname e.g. /en/pagepath1/pagepath2.
I've created a script below to define this.
There is a small complication here in that some of the pages already have the country/language variation passed in the URL so I have a regular expression to search for the market/language ISO code (lower case) to help perform an if statement that returns document.location.pathname where this is the case.
My script below however, seems to be fine but in testing it is returning "undefined" does anyone why this must be the case?
function PagePath() {
var StandardPagePath = document.location.pathname;
var NewPagePath = dataLayer.language.substring(0, 2) + document.location.pathname;
var LocaleRegExPatt = /^(at|cn|cz|de|dk|en|eu|fr|it|nl|no|pl|pt|pt-br|se)\//
try {
if (StandardPagePath.includes(LocaleRegExPatt)) {
return (StandardPagePath);
} else {
return (NewPagePath)
}
} catch (err) {}
}
My second question is how can I reference this function to pass through to the page tracking i.e. set the page here:
ga('set', 'page', {{PagePath function here}} );
Thanks in advance

Related

Best (and secure) way to call javascript function (with arguments) using a url from another page

After reviewing dozens of Stack Overflow posts, I'm thoroughly confused. What I am trying to do is create a URL through an tag on one page that would open another webpage and run a function that requires two arguments. I thought this would be simple but I keep seeing references to "cross site scripting vulnerabilities" and I am not familiar with this potential security problem and feel like I am now playing with fire. I do not want to utilize something — even if the code works — if it opens up security risks. Could someone point me in the right direction with the correct (and most secure) way to do this? I can do my research (and learning) from there. Much appreciated.
For example you can append some parameter at the end of your URL
https://your-url/?parameter=hello
When this URL is opened on another webpage you can run JavaScript or a PHP function based on that URL query.
For JavaScript
getUrlParam(slug) {
let url = new URL(window.location);
let params = new URLSearchParams(url.search);
let param = params.get(slug);
if (param) {
return param;
} else {
return false;
}
}
console.log(getUrlParam('parameter'));
After that, you can run this function to check if any parameter is passed in that URL or not.
If this function returns that's given slug parameter you can run your custom code inside that if condition block

GTM & Optimize : JS Variable is undefined but in console it works well

I'm trying to show the Google Optimize variant in Google Tag Manager.
I tried to implement it by "Custom JavaScript Variable":
function() {
var property = window.keys(gaData);
var experiment_nr = window.keys(window.gaData[property].experiments);
var experiment_value = window.values(window.gaData[property].experiments).toString()
if (experiment_value == "") {
return "0"
} else {
return experiment_value
}
}
This is the result of it:
Then I tried to test my code with a 5 sec delayed trigger:
And this is the result of the DevTools JS console:
As you can see, the console does not accept it with GTM but accepts it when I type it manually in.
Can someone help me there?
The answer was actually quite simple.
Google Optimize uses a cookie called _gaexp.
There, you get a string summing up the Google Optimize experiment ID as well as the version at the very end:
GAX1.2.wHL2IJUnSg2n8PB4iQH66w.18362.1
All I had to do was to create a new variable reading the cookie:
New variable
1st Party Cookie with the cookie name "_gaexp"
You can of course get the cookie name with JavaScript by simply calling Cookies.get('_gaexp') from the DevTools Console (to check if the cookie value is right)
The _gaexp value has to be manipulated to isolate the variant:
New variable
Custom JavaScript
Add the following code:
function (){
if ({{GA_Optimize_Variable}}=='undefined'){
return '0'
} else {
return {{GA_Optimize_Variable}}.charAt({{GA_Optimize_Variable}}.length-1)
}
}
The _gaexp is not existant when Google Optimize leads your traffic to the original variant of the website. Therefore, a if statement is needed.
Finally, you can use your variable in Google Analytics events and/or dimension.
Try to using dataLayer instead of window object.

JS window.location.href not showing same value as in address bar

I need to read the url using some JS code in order to extract some parameters and execute some tasks depending on them. However I have two problems:
-The webpage is not mine so I cannot modify anything on it or inspect it in great detail. I just write some script that the client load from its webpage, and executes some functions on load. I can modify this script but not anything else.
-In this functions, I save in a variable the window.location.href value, but when doing some logs in order to verify what is reading, I see that the value does not correspond to the actual url in the address bar. Moreover, if I check the value of window.location.href in the browser console, then the value matches with the address bar!
I check this value at the start of my script and at the end and it does not match in any case. I don't know at which point of the loading does my script start execution, and I don't know what is causing this behaviour.
EDIT: Here is some code, I won't show it all as most of it works fine and doesn't have relation to my problem.
This is what I sent to my client to put in its webpage:
var s1 = document.createElement('script');
s1.src = 'source_of_my_script;
document.head.appendChild(s1);
s1.onload = function () {
s();
};
This is part of my script:
function s(){
var my_url_var = window.location.href;
console.log("1st value", my_url_var);
var param = extractParamFromUrl(my_url_var); //this functions get some value written in the url
switch (param){
case 'value_0':
// do things
case 'value_1':
// do other things
defalut:
// do default actions
}
console.log("final value", window.location.href);
}
I cannot show you the exact URLs because of privacy reasons, but they are similar to these ones:
Address bar url (and what i get if I check window.location.href in browser console): https://www.client_dummy_url.com/dummy/cobranded?origin=8000097& ... (more params separated by &)
What I get from window.location.href in script: https://www.client_dummy_url.com/drfd01/main/control.do?action=start&internet=S&app=EP& ... (more params, but not all the ones I want!)
Many thanks!
After some tries, I managed to get it to work with the solution posted by #Vaibhav at Access parent URL from iframe
//var my_url_var = window.location.href;
var my_url_var = (window.location != window.parent.location)
? document.referrer
: document.location.href;

Attempting window.location or window.location.href redirect which is causing a loop

I'm attempting to use javascript to determine if the user is using a certain language and if they're not using english then for the page to load a different page BUT with the params of which I've grabbed from the url.
I have been able to load the page with the params but I keep falling into a loop reloading the page, even after skimming through the countless other examples, such as: this or this.
function locateUserLanguage() {
var languageValue = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)).split('-');
var url = window.location.href.split('?');
var baseUrl = url[0];
var urlParams = url[1];
if (languageValue[0] === 'en') {
console.log('no redirect needed, stay here.');
} else {
// I tried to set location into a variable but also wasn't working.
// var newURL = window.location.href.replace(window.location.href, 'https://www.mysite.dog/?' + urlParams);
window.location.href = 'https://www.mysite.dog/?' + urlParams
}
} locateUserLanguage();
I've attempted to place a return true; as well as return false; but neither stop the loop.
I've tried window.location.replace(); and setting the window.location.href straight to what I need, but it's continuing to loop.
There is a possibility that the script in which this function is written is executed in both of your pages (english and non-english) on load. So, as soon as the page is loaded, locateUserLanguage function is executed in both english and non-english website causing the infinite loop.
You need to put a check before you call locateUserLanguage function.
Suppose english website has url = "www.myside.com" and non-english website has url "www.myside.aus". So the condition needs to be
if (window.location.host === "www.myside.com") { locateUserLanguage() }
This will make sure that locateUserLanguage is called only in english website.
Or other apporach can be to load this script only in english website which will avoid the usage of conditional statement.
Hope it helps. Revert for any doubts.

Browser does not replace an include file by its including file

I am an absolute beginner in JS.
1) What I'm trying to do:
My web pages are composed of an index.php which is the same for all the files of a directory and one of a set of content.inc, like this: index.php?open=content.inc. This is done by a PHP snippet in the index.php and works well.
However, Google indexes all the content.inc files. The user's browser then displays the content.inc without the framing index.php. This I want to avoid. I therefore add a modest script at the beginning of each content.inc (which I would convert into a function once it runs) to tell the browser that instead of displaying the content.inc, it should display index.php?open=content.inc.
2) My unworkable solution:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
if (filename.indexOf("index.php") = -1)
{ var frame_name = "index.php?open="+filename;
window.location.replace(frame_name);
};
The browser (Firefox 60) ignores this; it displays content.inc. (I also have versions of this script which get the browser into an endless loop.)
What is wrong here? Please help!
PS: Please be assured that I have done extensive web search on this problem and found many pages of complaints about location.replace getting into an infinite loop; but none matches my situation. However, I gratefully accept a helpful link as an answer.
For starters, you have an error in this line:
if (filename.indexOf("index.php") = -1)
That's an assignment and will always evaluate to true, you need to use == or === (which should be more performant).
The guilty line is on your test case (see JP de la Torre answer). And to improve, here's a snippet to demo how to analyze the url with a regular expression :
function redirect(url) {
if(url && url.indexOf('.inc') >= 0) {
return url.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
return url;
}
let urls = [
window.location.href,
'http://google.fr',
'http://example.com/index.php?open=wazaa',
'http://example.com/wazza.inc'
];
urls.forEach(url => {
console.log(url, ' => ', redirect(url));
});
The regexp will capture any text between a / and .inc. You can use it then as replacement value with the $1.
And applied to your case, you simply need :
if(window.location.href.indexOf('.inc') >= 0) {
window.location.href = window.location.href.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
You can also use .htaccess server side to redirect request for .inc files on your index.php if mod_rewrite is enabled.
The solution to the problem of including an INC file called separately is the one proposed by Bertrand in his second code snippet above. It presupposes (correctly) that the inc extension is omitted in the replacement.
As I reported above, Firefox may get into an endless loop if it opens a PHP file directly, i.e. without involving the local host (with its php module).

Categories

Resources