I've been using Google analytics trackPageview for a while and recently used the following js function to track some form submit button, which is to grab the current url and add some parameters to it. Things work fine, except that the URL that I see in the report is /https://www.mysite.com?pg=confirm (with a forward slash at front), instead of https://www.www.mysite.com?pg=confirm as I wanted. How to remove that slash? Thanks!
function trackGoogle(btn){
var curl = document.URL;
var confirm_url;
if (btn == 1){
confirm_url = curl + '?pg=confirm';}
else {confirm_url = curl + '?pg=confirm';}
_gaq.push(['_trackPageview', confirm_url]);
}
Analytics generates your pageview reports relative to the site's root for the property/profile you're viewing. The confirm_url parameter you're passing to GA is assumed to be the relative path (excluding the domain) from the site's root. In other words, the preceding slash stands for "www.mysite.com" and so confirm_url should be "?pg=confirm"
Related
I am working on a plugin to modify a URL and update a page. The goal is to get the parent URL, modify it and then offer up a link that the user can click to go to the new URL.
I am able to get the URL and display it, then modify the URL and display it. However, when I try to create a link using the ID, the link URL is to the index.html for the iframe, not the newURL id that I am referencing. I know I am overlooking something but I have been through a ton of HTML documentation and can't solve it. Any help would be greatly appreciated. Image of bad URL
Thanks,
Scott
<!DOCTYPE html>
<html>
<body>
<p id="currentURL"></p>
<p id="newURL"></p>
Click this link to update sort
<script>
var myAssetsServer = "http://localhost:8080"
var startingURL = parent.document.location.href;
var myCustomSort = "imageSupplierImageID,assetType,filename";
var endingURL = myAssetsServer + "/app/#/search//" + myCustomSort + "/?" + startingURL.split("?")[1];
document.getElementById("currentURL").innerHTML =
"The original URL of this page is:<br>" + startingURL;
document.getElementById("newURL").innerHTML = endingURL;
</script>
</body>
</html>
The two main issues to address were
Update the href value of the link element (from comment not an issue in actual code), and
Percent encode the # character as %23 in the URL to send it and what follows to the server:
Hash marks in a URL that are part of identifying a a resource on the server must be percent encoded.
By contrast, fragment identifiers at the end of an URL, e.g.
htpp://www.example.com/page.html#element-id
are used by browsers to request a page from the server and, after rendering the response, scroll down the page to the element with the same id as the fragment identifier.
The first raw hash mark (not the last occurrence) in a link's 'href` string introduces a fragment identifier.
Neither the fragment identifier nor its preceding '#' character are sent to the server as part of a request: they terminate a URL without forming part of it.
See also
Related What are fragment URLs and why to use them?
The description of unsafe characters in section 2.2 of RFC1738
The character "#" is unsafe and should
always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might
follow it.
Additional issues may need addressing, depending on how the server application is written - or whether the posted code is final:
the double slash // in the URL looks strange but could be by design.
Comma characters in a URL are meant to be encoded as %2C unless being used as separators in the query component. They may work anyway, due to there being no assigned meaning of commas placed before the beginning of the query component, and server code may or may not impose a requirement for their usage (check with the developer).
When running the snippet on Stack Overflow, a dummy page location had to be set (example.com), which then generated undefined in the query component of the generated href value.
Example code snippet with fixes for 1 and 2:
"use strict";
var myAssetsServer = "http://localhost:8080"
var startingURL = "http://www.example.com"; //parent.document.location.href;
var myCustomSort = "imageSupplierImageID,assetType,filename";
var endingURL = myAssetsServer + "/app/#/search//" + myCustomSort + "/?" + startingURL.split("?")[1];
//Fix 1: escape the '#' in the URL
endingURL = endingURL.replace('#', "%23");
document.getElementById("currentURL").innerHTML =
"The original URL of this page is:<br>" + startingURL;
document.getElementById("newURL").innerHTML = endingURL;
//Fix 2: change the URL in the link
var anchorElement = document.querySelector("a[href=newURL]");
anchorElement.href = endingURL;
//Prevent link action on Stack Overflow:
anchorElement.addEventListener("click", function (event) {
console.log("href= %s", this.href)
event.preventDefault();
});
<p id="currentURL"></p>
<p id="newURL"></p>
Click this link to update sort
<p style="border-left: medium solid #DDD; padding-left: 2rem;">
Link deactivated in code snippet - hover over or click to see href value.
We are using gatsby to develop our website and I am using the gatsby-plugin-google-tagmanager plugin in order to fire google analytic events..
One issue we face is that when the user visits our site from utm links the session seems to split the exact same second he lands on the page.
What I do so far
Fire a Page View Google Analytics: Universal Analytics tag using the gatsby-route-change trigger.
GA debug report
One thing that seems abnormal is that on every route change, using the GA Debug tool, a new Creating new tracker log is created.
Ways I tried to fix this
Read an article that on single page applications you might get faulty values for page, location and referrer properties, so this fools google analytics to create a new session each time, so that might be the reason why the session breaks.
What I tried to do was to override these values in the GA tag. However, this does not seem to fix the issue.
// Location override gtm variable
function () {
return window.document.location.protocol + '//' +
window.document.location.hostname +
window.document.location.pathname +
window.document.location.search
}
// Referrer override gtm variable
function () {
return window.history.state.referrer
}
// Page override gtm variable
function() {
var path = window.location.pathname + window.location.search + window.location.hash
var index = path.indexOf('?');
if(index > -1){
path = path.substring(0, index);
}
return path;
}
Got any idea on this? Is it possible that this behavior splits our session? Is there anything else you recommend?
https://www.simoahava.com/gtm-tips/fix-rogue-referral-problem-single-page-sites/
This article answers the question.
With Google Tag Manager, every single Universal Analytics Tag that fires on the site creates a new, unique tracker object. This means that the Document Location field is updated with every Tag you fire, which is a problem if the URL changes due to browser history manipulation. Thus you can end up with a situation where the first Universal Analytics Tag has gclid in the URL, attributing the session to AdWords, but the next pageview doesn’t have this in the URL anymore, as you would not include it in the “virtual” pageview path names. Instead, since gclid is no longer in the URL, GA looks at the HTTP referrer of the page to see what the previous page was for attribution. It finds google.com, as you came from the search engine (HTTP referrer is not updated when manipulating the URL with the browser History API). Thus a new session starts with attribution to Google Organic! I’ve dubbed this as the Rogue Referral problem.
Solution
Manually Set Document Location To Prevent Rogue Referrals
Create a script to save the landing URL in the dataLayer
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
originalLocation: document.location.protocol + '//' +
document.location.hostname +
document.location.pathname +
document.location.search
});
Create a script variable to get the current page. (if you don't need hash remove it)
function() {
return window.location.pathname + window.location.search +
window.location.hash
}
Add variables to all you Universal Analytics by manually setting the fields location and page
I have two pages on MyDomain.com. The index view which is visible from MyDomain.com/ and MyDomain.com/Foo/Bar. Each view has an ajax call to the other and each one pushes the state using the HTML5 History API.
There are the steps that create the problem:
Start at MyDomain.com/ (Works as expected.)
Click the ajax link to MyDomain.com/Foo/Bar/ (Works as expected.)
Click the ajax link to MyDomain.com/ (Works as expected.)
Click the ajax link to MyDomain.com/Foo/Bar/
Now the URL appears as MyDomain.com/Foo/Foo/Bar/
I don't want a Foo Foo Bar.
My current workaround is to add "../../../" to the front of the URL, but this is inelegant and not foolproof. Another option is a regex expression to count the directory levels.
Is there a better way to get absolute URLs with the History API?
function push(updateElementID, controller, action, url)
{
if (typeof url == "undefined")
{
url = "/" + controller + "/" + action;
}
var state = {
id: updateElementID,
controller: controller,
action: action
}
history.pushState(state, null, url);
}
You may want to ensure that the base element of the href element in the DOM is cleared...at least in the following case, it works for me: On your shared layout page (_layout.cshtml), reset the absolute URL within the DOM by placing the following within the head tags:
<base id="htmldom" href="http://localhost:59805/"/>
of course replacing your port # and on launch, replacing the root URL to the actual domain name.
By doing this, you are setting, or resetting the href property and specifying a base URL for all other relative URLs.
Now would doing it this way would affect any user-input data preserved in the page between back and forward buttons? I'm guessing it would be fine, as the above only resets the href property, and any other info in the DOM should be there.
Essentially, I have this website, the content of which changes depending on what the user inputs into the query string.
When the user enters mysite.com/?1 it loads content for 1 and /?2 for 2
My problem is that I have a Facebook like button within my page, and to make it work I have written this js code:
<script type="text/javascript">
var sUrl = window.location;
document.getElementById('fbcom').setAttribute('href', sUrl);
</script>
this gets the url and allows the user to like different content from what is technically one file.
My problem is that when a user likes for example /?1 on facebook, if someone where to click this link on their newsfeed and decide that they like it too, technically they will be liking the page /?1-with all the additional facebook code on the end of the url, so heading back to /?1 the like has not registered.
How can I modify the above code to ignore any facebook rubbish on the end of the url when they are directed from facebook?
Important: the ID /?1 can be anything from a 1 digit to a 4 digit number e.g /?1234
My current JS ability is very poor. Thanks
You can combine the properties of location you actually want to keep -- which seems to be protocol, host, and pathname:
var sLoc = window.location;
var sUrl = sLoc.protocol + '//' + sLoc.host + sLoc.pathname;
You can also just use the pathname as relative-from-root:
var sUrl = window.location.pathname;
you can do that with regex:
var sUrl = window.location.toString().replace(/^(.*?)(\?.*)?$/, '$1');
I was on Facebook and realised that when I change page the page address changes but the page does not redirect but loads via ajax instead.
You can tell because the console does not clear when you click the link but the URL changes.
Weird, but anyone know how it is done?
Facebook runs with massive AJAX calls that changes the page state and the sections.
So to make a page linkable to somebody by copying the URL address, every time you call an AJAX relevant function they updates the URL using a fake anchor "#!" plus the real address.
Simply when you load the real page (using F5 or linking that so somebody) a JS parser catchs the string after #! (if there is) and redirect you to baseaddress + that.
I belive something like this (untested):
var urlstr = new String(location.href);
var urlparm = urlstr.split('#!');
var last = urlparm.length - 1;
if( (urlparm[last] != urlparm[0]) && (urlparm[last] != "/") )
{ var redir = "http://www.facebook.com" + urlparm[last];
location.href = redir;
}
In Google Chrome instead the URL really changes, I'm according that there is an hash somewhere, but I don't know where and how.