How Can I Pass a Parent Cookie into an iFrame src? - javascript

So I have embedded iFrame forms on my site and need to implement persistent tracking for users, meaning that their UTM parameters pass between pages and then get submitted into hidden fields with the form.
I believe the best way to do this is by setting a cookie to capture the UTM params on the parent site (done), and then reading the cookie to set a query string on the iFrame src. From there, I can pass the hidden values from the iFrame src (that's also already done).
What I'm having trouble figuring out is how to connect the dots. and have searched around quite a bit without finding a clear answer. And I'm showing my work but certainly open to other suggestions.
So I have these code snippets...
First, just above the iFrame embed, there's this:
const getCookie = (__gtm_campaign_url) =>{
// Construct a RegExp object as to include the variable name
const re = new RegExp(`(?<=${cookie_name}=)[^;]*`);
try{
return document.cookie.match(re)[0]; // Will raise TypeError if cookie is not found
}catch{
return "this-cookie-doesn't-exist";
}
}
getCookie('__gtm_campaign_url') //
getCookie('_non_existent') // this-cookie-doesn't-exist
Then, to generate the iFrame embed:
var form = 'https://go.mysite.com/some-unique-ids';
var params = window.location.search; // I know this needs to change, just don't know how
var thisScript = document.scripts[document.scripts.length - 1];
var iframe = document.createElement('iframe');
iframe.setAttribute('src', form + params);
iframe.setAttribute('width', '100%');
iframe.setAttribute('height', 500);
iframe.setAttribute('type', 'text/html');
iframe.setAttribute('frameborder', 0);
iframe.setAttribute('allowTransparency', 'true');
iframe.style.border = '0';
thisScript.parentElement.replaceChild(iframe, thisScript);
Finally, within the iFrame, there's this snippet to parse the cookie and get it into the proper hidden fields. Frankly, this is leftover from something else I've tried but didn't work, so it could/should be eliminated if I could get the cookie parsed into var params = [foo] above, but including it for reference:
// Parse the Cookie
function getCookie('__gtm_campaign_url') {
var name = __gtm_campaign_url + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// Parse the URL inside Cookie
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
results = regex.exec(getCookie("__gtm_campaign_url"));
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Pass the values to hidden field
document.querySelector("input#input_3_9").value = getParameterByName('utm_source');
document.querySelector("input#input_3_9").value = getParameterByName('utm_term');
document.querySelector("input#836443_81170pi_836443_81170").value = getParameterByName('utm_medium');
document.querySelector("input#input_3_8").value = getParameterByName('utm_campaign');
document.querySelector("input#input_3_11").value = getParameterByName('utm_content');

Related

Storing and Retrieving a JSON Obj from a Cookie

I have looked at many SO and haven't been able to figure out how to actually make this work using pure JS. My problem is that I need to add a 2 different urls to a json array and store it into a cookie for access across subdomains (i looked into the iframe local storage thing and it won't work for this application and the json array will be rather small so 4k cookie limit is plenty).
Now what I have is the following:
function getProject(){
var url_str = window.location.href;
var ProjectImgId = url_str.split('projectId=')[1];
ProjectImgId = ProjectImgId.split('&')[0];
var UserId = url_str.split('flashId=')[1];
var ImageURL = 'https://project-api.artifactuprising.com/project/' + ProjectImgId + '/thumbnail?user=' + UserId;
var RecentProjects = {"url" : url_str, "img" : ImageURL};
return RecentProjects;
}
The above will run on a certain page load. I want to be able to do the following with this: retrieve any existing Projects and if there isn't a match on the url, I wan to push the RecentProjects to the cookie array.
Here is where I am getting stumped. I am following w3 School's cookie set up which has worked for me in the past but I am unable to figure out how to push and pull this data using stringify and parse.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var recent = getCookie("yourRecentProjects");
if (recent != "") {
// this is where I would want to parse the JSON and then check if the getProject.url value is in the current cookie json and if it is not, push it.
} else {
recent = getProject();
if (recent != "" && recent != null) {
setCookie("yourRecentProjects", recent, 365);
}
}
}
I am pretty stumped. I have figured out how to do all this using local storage, then i realized this doesn't work across subdomains so great learning experience but not a solution. Any help would be appreciated.
well, the cookie isn't json, it's just a string with a bunch of key values.
not 100% what you are looking to do with the data, but as an example, this is taken from the MDN, example #3, as for how to parse that string to find a specific value: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie:
function doOnce() {
if (!document.cookie.split('; ').find(row => row.startsWith('doSomethingOnlyOnce'))) {
alert("Do something here!");
document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
} }
String.prototype.split() creates an array of substring segments that are delimited by the value you pass in, the Array.prototype.find() will look at each value in the array until it either finds the substring that starts with that value, or returns undefined if it finds nothing.
In you case, you'd do document.cookie.split("") to create the array of key value substrings, which at that point you can unpack the data in many ways. maybe you are just looking for the existence of the url value, in which case Array.prototype.includes() is what you are looking for.

Storing parsed URL in Cookie (not storing the entire value)

TL;DR: I am forced to use a javascript solution to store a URL parameter as a cookie, but when the function runs, it only stores the first 5 characters of the value I need.
I am working on implementing affiliate sales tracking across domains. As stated above, I need to store a value from a URL in a cookie so that I can pull it into a separate (functioning) script later. On my primary domain, I was able to do this with a simple .php script, but the third-party platform we use for our sales doesn't allow me to run .php scripts, so I found a javascript function that seemed to be working prior to today. That said, prior to today I was using test parameters that were only numerical (1234567890, etc.).
Here is an example of the kind of URL and parameter being used:
https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0
This is the function I've been using successfully up until now:
function getParameterByName(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
results = regex.exec(location.search);
return results === null
? ''
: decodeURIComponent(results[1].replace(/\+/g, ' '));
}
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
For some reason, the function now only stores the first 5 characters of the value, or "QW6Qn" in this case. Any help or direction on how to make this work correctly is appreciated.
Resolution:
I found a function that was more apt for what I needed here on stackoverflow: How to get parameter name?, and replaced the first part of my javascript with the following, and it is now working as expected!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
The last section remained the same:
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
Thank you to those that offered help and insight.
const url = new URL('https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0')
document.cookie = `irclickid=${url.searchParams.get('irclickid')}; expires=...`
You can see on https://caniuse.com/url if all required browsers support URL.

How to pass a querystring with javascript and use it in codebehind page in asp.net?

Currently I am opening a page in dialog box as shown below using JavaScript. I am passing a query string by encrypting it to the list page .
function Popup() {
if (document.getElementById("<%= Amount.ClientID %>").value != "") {
var xorKey = 13;
var Obj = window;
var id = document.getElementById("<%= id.ClientID %>").value + "-" + document.getElementById("<%= Amount.ClientID %>").value;
var result = "";
for (i = 0; i < id.length; ++i) {
param += String.fromCharCode(xorKey ^ id.charCodeAt(i));
}
window.showModalDialog("list.aspx?id=" + param, Obj, "dialogWidth:800px; dialogHeight:500px; dialogLeft:252px; dialogTop:120px; center:yes");
}
}
Now on code behind page I am using this code :
string id = Request.QueryString[0].ToString();
StringBuilder inSb = new StringBuilder(id);
StringBuilder outSb = new StringBuilder(id.Length);
char c;
for (int i = 0; i < id.Length; i++)
{
c = inSb[i];
c = (char)(c ^ 13); /// remember to use the same XORkey value you used in javascript
outSb.Append(c);
}
string[] idvalue = outSb.ToString().Split('-');
id = idvalue[0].ToString();
Now when using the Querystring[0] I am only getting the pre decimal values like if the value I type in textbox is 13.33, then I am on the list page getting only 13. Can anybody help me?
Thank you.
Use escape on the param variable as follows
window.showModalDialog("list.aspx?id=" + escape(param), Obj, "dialogWidth:800px; dialogHeight:500px; dialogLeft:252px; dialogTop:120px; center:yes");
or encodeURI
window.showModalDialog(encodeURI("list.aspx?id=" + param), Obj, "dialogWidth:800px; dialogHeight:500px; dialogLeft:252px; dialogTop:120px; center:yes");
Use encodeURIComponent() to encode your url before sending it to the server.
http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp
Edit: Added link to source.

replace url parameter and text using jquery?

When I click search button the url parameter is taking care of. I need to change that url parameter name and value using jquery.
per example: search button clicked
http://testsite/_layouts/OSSSearchResults.aspx?k=deana&cs=This%20Site
Replace with:
http://testsite/_layouts/OSSSearchResults.aspx?k=deana&s=All%20Sites
I can not modify search button functionality, because it is out of the box functionality.
I can do changing url parameter and value. How can we do that?
Changing the parameter of a URL should be fairly straightfoward:
var param = window.location.href;
var param_q = param.split('?');
var param_ampersand = param_q[1].split('&');
var param_eq_1 = param_ampersand[0].split('=');
var param_eq_2 = param_ampersand[1].split('=');
var new_param_name_1 = 'test';
var new_param_value_1 = 'example';
var new_param_name_2 = 'test2';
var new_param_value_2 = 'example2';
// avoid infinite loop
if ((param_eq_1[0] != new_param_name_1 || param_eq_1[1] != new_param_value_1) || (param_eq_2[0] != new_param_name_2 || param_eq_2[1] != new_param_value_2)) window.location = param_q[0] + '?' + new_param_name_1 + '=' + new_param_value_1 + '&' + new_param_name_2 + '=' + new_param_value_2;
This worked for me in Chrome/FF. This just redirects the parameter - not sure if this is what you're looking for.
EDIT:
Added a logic to handle two parameters.

Append to URL and refresh page

I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?
this should work (not tested!)
var url = window.location.href;
if (url.indexOf('?') > -1){
url += '&param=1'
}else{
url += '?param=1'
}
window.location.href = url;
Shorter than the accepted answer, doing the same, but keeping it simple:
window.location.search += '&param=42';
We don't have to alter the entire url, just the query string, known as the search attribute of location.
When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.
Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:
location.href = location.href + "&parameter=" + value;
This will work quite well for the majority of the cases.
However
That's not the correct way to append a parameter to a URL in my opinion.
Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:
https://stackoverflow.com/?&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1
at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){
var hash = {};
var parser = document.createElement('a');
parser.href = url;
var parameters = parser.search.split(/\?|&/);
for(var i=0; i < parameters.length; i++) {
if(!parameters[i])
continue;
var ary = parameters[i].split('=');
hash[ary[0]] = ary[1];
}
hash[param] = value;
var list = [];
Object.keys(hash).forEach(function (key) {
list.push(key + '=' + hash[key]);
});
parser.search = '?' + list.join('&');
return parser.href;
}
With this function one just will have to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
location.href = location.href + "&parameter=" + value;
This line of JS code takes the link without params (ie before '?') and then append params to it.
window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";
The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).
function gotoItem( item ){
var url = window.location.href;
var separator = (url.indexOf('?') > -1) ? "&" : "?";
var qs = "item=" + encodeURIComponent(item);
window.location.href = url + separator + qs;
}
More compat version
function gotoItem( item ){
var url = window.location.href;
url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
window.location.href = url;
}
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'&param='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
One small bug fix for #yeyo's thoughtful answer above.
Change:
var parameters = parser.search.split(/\?|&/);
To:
var parameters = parser.search.split(/\?|&/);
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets

Categories

Resources