Capture incoming URL parameters & pass into a div's "data-url" attribute - javascript

We are currently using a typeform that is embedded in our site. All of the traffic driven to our site is from cpc campaigns so accurate conversion tracking in GA is a must so we can accurately track our ROI.
Here's the problem. When sending cpc campaigns to the directly to the typeform URL the GA tracking was accurate. After embedding the typeform into our site the GA tracking shows that the referrer is our site, and not Google or Bing cpc.
Without making this too long of a post, I need to be able to capture the campaign parameters (utm source, utm medium, etc) in the URL & input that data into a "data-url" attribute located in a div.
Right now this is the code i have:
function main () {
var loc = window.location.toString(),
params = loc.split('&')[1],
params2 = loc.split('&')[2],
params3 = loc.split('&')[3],
params4 = loc.split('&')[4],
params5 = loc.split('&')[5],
typeformWidget = jQuery("#typeformWidget");
typeformWidget.attr('data-url') == typeformWidget.attr('data-url') + '?' +
params + '&' + params2 + '&' + params3 + '&' + params4+ '&' + params5;
console.log(params);
};
main();
I appears that the correct parameters are being captured when I see the data in the console, however I cannot for the life of me figure out how to pass the data to the "data-url" attribute.

typeformWidget.attr('data-url', typeformWidget.attr('data-url') + '?' +
params + '&' + params2 + '&' + params3 + '&' + params4+ '&' + params5);
OR
typeformWidget.data('url', typeformWidget.data('url') + '?' +
params + '&' + params2 + '&' + params3 + '&' + params4+ '&' + params5);
The reason your code does not work is that == is used to compare equality usually used in if statements. To assign a value you use = but with jQuery you need to use the method to assign the value in this case .attr('attribute name', value) or the .data('name after the data-', value)

Classes and names have changed in the latest versions of Typeform this is how I got it to work.
You will need to load jQuery, this one or latest version:
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Then you basically just take the URL in JavaScript and split the part you want and then replace the URL that loads the embebed form to pass the UTM tag of the initial website , then add this script before </body>:
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
//this where your utm tags should be going given your URL looks like: https://www.whatever.com?utm_source=Facebook you can
//build your URLs here: https://ga-dev-tools.appspot.com/campaign-url-builder/
const utm_source = urlParams.get('utm_source')
typeformWidget = $("[data-url]");
//the hidden field's name you created at typeform must go here, for this example the field is named: 'source',
newurl=typeformWidget.attr('data-url')+'?source='+utm_source;
//you need to load jquery for this
$("[data-url]").attr("data-url", newurl);
</script>
Υou can add more fields but you need first to get them (check above) and then adjust the new url line, it would be typeformWidget.attr('data-url')+'?source='+utm_source+'?medium='+utm_medium etc. etc.;
Github for the script

Related

Removing Query Strings from the URL Using Google Tag Manager

I'm trying to tidy up the analysis in Google Analytics by removing query strings from the URL, but this has split into three requirements;
I want to remove query strings from being displayed in the GA analysis.
Campaign UTMs still need to work.
Stop any PII gathered in a UTM from hitting GA.
I've found a number of JavaScript methods (attached below) that will do task 3, but I don't know whether this implementation will affect tasks 1 and 2.
This leads to my question;
Will the JavaScript method stop all query strings from hitting GA entirely, and therefore break my campaign UTMs?
Thanks for your help!
JavaScript attached below
function() {
var params = ['name', 'email'];
var a = document.createElement('a');
var param,
qps,
iop,
ioe
i;
a.href = {{Page URL}};
if (a.search) {
qps = '&' + a.search.replace('?', '') + '&';
for (i = 0; i < params.length; i++) {
param = params[i];
iop = qps.indexOf('&' + param + '=');
if(iop > -1) {
ioe = qps.indexOf('&', iop + 1);
qps = qps.slice(0, iop) + qps.slice(ioe, qps.length);
}
}
a.search = qps.slice(1, qps.length - 1);
}
return a.href;
}
If you update the page location in the DOM with the result of a function like this (window.location={{clean URL}}) you would naturally cause a lot of problems by causing reloading.
If you use the result of this function to set UA parameters relating to page and referrer, then it affects nothing that isn't related to those parameters in the hits. For example, you would want to clean the page field which is not just on page hits:
Things like utm parameters are extracted from normal DOM/BOM (for example window.location) and sent as separate parameters and are not calculated from page related parameters later on the server side unless you are doing extraction yourself in Analytic's custom filters.
Also you may use Google Analytics built-in mechanics to drop URL parameters through setting up Exclude URL Query Parameters in View settings. Docs are here: https://support.google.com/analytics/answer/1010249?hl=en
No JS Required.

.load function went wrong if there is anchor (#) in URL

My page have some parts that will be populated by .load()
$(document).ready(function() {
if (document.getElementById('add_to_userlist')) {
$('#add_to_userlist').load(script_name + '?' + nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=v_funcs&mod_list=user_playlist' + '&id={DETAIL.id}' + '&fcheck={DETAIL.check_session}' + '&nocache=' + new Date().getTime());
}
if (document.getElementById('favourite-{DETAIL.id}')) {
$('#favourite-{DETAIL.id}').load(script_name + '?' + nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=v_funcs&mod_list=get_fav' + '&id={DETAIL.id}' + '&fcheck={DETAIL.check_session}' + '&nocache=' + new Date().getTime());
}
$(".bodytext_shorten").shorten({showChars: 200});
});
Everything is okay but if there is an anchor in this URL, like :
http://nukeviet-hvt.rhcloud.com/videos/chuyen-muc-1/sau-tim-thiep-hong-giao-linh-ft-tuan-vu-2.html#comment_box
The page does not load as it should. The div with id id #add_to_userlist and favourite-{DETAIL.id} load entire of page instead of a HTML part only.
So the page keep reload and enable my flood blocker.
I think there is a conflict but don't know how to solve it.
Google Chrome show this in Console
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
The jQuery load method doesn't support fragment identifiers in URLs to determine which part of a document to load.
The syntax it supports is a space followed by a CSS selector.
.load("http://nukeviet-hvt.rhcloud.com/videos/chuyen-muc-1/sau-tim-thiep-hong-giao-linh-ft-tuan-vu-2.html #comment_box")
It isn't entirely clear from the question, but it looks like you have that value in script_name and then are trying to add the query string after it.
In a URL the query string must appear before the fragment identifier.
In load() syntax, the selector must appear after the entire URL (i.e. after the query string and after any fragment identifier).

Save and update information in the Url

I have two carousels, each with their own id "sliderId", and then i have an id on all the elements within the carousel, so i know how far they have scrolled, "currentFirstId".
I would like to save the indformation in the url, and I have done that by writing:
window.location.href = currentLocation + "#" + sliderId + "=" + currentFirstId;
that give me the result i whant: www.blabla.com/#sliderId?2296=0#sliderId?2337=0
But how do git it to update currentFirstId when I scroll, because as it is now, it's put's the information after already existing text like this:
www.blabla.com/#sliderId?2296=0#sliderId?2337=1#sliderId?2296=0#sliderId?2337=2#sliderId?2296=1#sliderId?2337=3#sliderId?2296=2#sliderId?2337=4.
So how do i get it to update the already existing text, so the output is:
www.blabla.com/#sliderId?2296=2#sliderId?2337=4 ???
I hope it makes sense.
Maybe try:
window.location.href = window.location.hostname + window.location.pathname + '#' + sliderId + '=' + currentFirstId;
Look at this Post:
URL without query string
Maybe you want to use window.location.origin and append the "#sliderId?2296=0#sliderId?2337=0" part to that rather that using currentLocation.

Changing how URL parameters are appended to links based on destination

My company is serving up PPC landing pages with Unbounce (on a subdomain), which then links back to our website. We're using the following code to append the AdWords gclid variable to outgoing links:
$(document).ready(function() {var params = window.location.search.replace(/\+/g,'%20'); var button = $('a').each( function(i) {this.href = this.href + params;});});
The issue arises when the Gclid gets appended to a URL that already has a parameter (like our checkout forms). You end up with a URL that looks like this:
domain.com/checkout?EventID=15546?Gclid=jdkI324kd
I'm wondering if there's a way to change the Glid's '?' to an '&' for certain URLs that already have parameters, while keeping the existing functionality of using the '?' for the others.
Thanks!
Edit: Seems like there's some redirection going on, this is how the href looks for the links in question:
http://domain.com/lp/clkg/https/domain.com/cart.aspx?EventID=125160?gclid=CPfO1JaOx7oCFQZyQgod5A4AFw
Simply replace it yourself:
$(document).ready(function() {
var params = window.location.search.replace(/\+/g,'%20');
var button = $('a').each( function(i) {
if (this.href.indexOf('?') == -1) {
this.href = this.href + params;
} else if (params.length) {
this.href = this.href + '&' + params.substr(1);
}
});
});
Edit: and are you aware that you are replacing subsequent spaces with only one single '%20'?

Create and go to url with Javascript

I want to be able to produce a URL based on certain properties and then go to the new URL in javascript.
Here is what I have so far:
triggerNumber = document.findcontrol(txtTrigNo).text;
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber
How do I navigate to the new URL?
Simply try:
window.location = url;
But before trying to do that, you have to make sure the page at the address "http://" + hostAddress "/" + triggerNumber exists. For example by putting valid triggerNumbers in an array and check if it exists or not. So:
//Not sure if at the end it should be .text or .value or .value()
triggerNumber = document.findcontrol(txtTrigNo).text;
var validTriggers = [123, 456, 789];
if (validTriggers.indexOf(parseInt(triggerNumber)) == -1) {
alert("Invalid trigger number");
} else {
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber;
}
Finally, if the destination is a server-side page (php, asp, etc), the address usually looks like this:
"http://" + hostAddress "/trigger.php?id=" + triggerNumber;
but you'd better use forms for this.
Edit: As Cerbrus suggested, validating the values with javascript is a good way to tell the user about his errors before navigating away from the page. But to make sure the correct data is sent to server, it is important to do the validation in the server-side code, too.
In this example, in case of an invalid trigger number the user may finally see a 404 error; but with sensitive information worse things can happen.
What you need is:
document.location.href = url;
After you have the URL in the url variable.
To get value of input element have:
var triggerNumber = document.getElementById("txtTrigNo").value;
This will get the hostname and port of the server, and concatenate the value of the element onto the end, and then go to the resulting URL.
var triggerNumber = document.getElementById("txtTrigNo").value();
var url = "http://"+window.location.host+"/"+triggerNumber;
window.location = url;

Categories