Split URL to set cookie using Javascript - javascript

Hoping you can help. I think I'm nearly there but my code has a slight error in it. I'm trying to set a cookie which sets the cookie value based on a section of the page url.
For example my cookie name is "model" and my cookie value is populated based on the url
https://www.website.co.uk/cars/100sr/
in the example above the cookie value should be set as 100sr
However, I've just noticed an error, where if the customer visits my website with a query string on the url, it's setting the cookie value to the query string content not the 100sr
e.g.
https://www.website.co.uk/cars/100sr/?testing
the url above using my current code would set the cookie as ?testing when I want it to still be set as 100sr. I'm guessing my code is taking the content after the LAST / is there perhaps a way to specify to take the content after the 2nd / instead?
Code below
<script>$("#carbtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str);
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>

If you use the pathname instead of the href, you'll be able to retrieve the portion of the URL without the query string. For example, on the URL:
Split URL to set cookie using Javascript
Using window.location.pathname returns:
"/questions/67402851/split-url-to-set-cookie-using-javascript"
So do:
$("#carbtn").bind("click", function() {
const strings = window.location.pathname.split("/").filter(str => !!str);
document.cookie = `model=${strings[strings.length - 1]};path=/;`
});

<script>$("#carbtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str);
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
This code gets the last element on the split of "/", so "/my/path/" gets the empty string after "path/[HERE]", you might need to dig into the awful (or wonderful) world of regexp for that
const lastItemOnURL = window.location.pathname.match(/[^\/]+\/?$/);
if (lastItemOnURL[0]) { document.cookie = `model=${lastItemOnURL[0].replace('/', '')};path=/;` }
Notice that window.location.pathname doesn't grab the eventual ?get=values in the URL so you probably need that too

Related

cypress: comparing information in 2 sites

I'm starting with cypress and need to compare 2 different environments.
I did a script, but is not working properly.
My goal is:
1 - search for a specific selector value at 2 different environments.
2 - get it's value (in both env) , and then compare it if equal.
The below comparision work, but seems very poor code and it stop in first error assert and can't query reference selector, just text.
Any help is appreciated.
describe('Testing Page', function() {
//urls i need to test
var relative_urls = [
'/products/test1',
'/products/test2',
]
relative_urls.forEach((url) => {
//each url is compared here...
var productInfo = [];
//here goes the environments URL.
var testURL = 'https://www.myurl.com' + url;
var referenceURL = 'http://test.myurl.com' + url;
it('Comparing data from url:' + url, function() {
cy.visit(testURL)
//get data from selector and add it to array
cy.get('body').find(".myselector h1").should(($input) => {
productInfo.push($input.val())
})
cy.get('body').find(".myselector h2").should(($input) => {
productInfo.push($input.val())
})
//requesting second url
cy.request(referenceURL)
.its('body').should( ($input) => {
for (var j=0;j<productInfo.length;j++) {
//expect works, but compares to all site, and i need to search in a specific selector.
//Also, when it gets the first error, it stops and do not search all elements of array
expect($input.includes(productInfo[j]), 'Notice: ' + productInfo[j]).to.be.true
}
}
})
})
})
})
From reading the documentation, cy.request is really making a plain HTTP request without doing any parsing, which means you basically have to parse the body of the response yourself. cy.visit will actually get the DOM elements so you can use Cypress's query syntax to navigate the page.
I think once you have the element values from the first page you should just do cy.visit again and parse the second page.
EDIT: Apparently you can't use cy.visit cross-domain. In that case, maybe you could try parsing the response body into a DOM node like this:
var el = document.createElement( 'html' );
el.innerHTML = request.body // you can get the request object from cy.request;
Then use el.querySelector to navigate the DOM tree using CSS syntax.

Real url not working for url build by javascript TYPO3

I configured the extension tt_address in my page. I need to filter the address by its year. So I build a select box. I need to append some query parameter with its url to access in controller for implementing the filter.
The functionality is done successfully. But realurl is not working for this particular functionality.
main.js
function initYearFilter() {
var selectedItem = sessionStorage.getItem('year');
if (selectedItem !== null) {
$('.year-filter select').val(selectedItem);
}
$('.year-filter select').on('change', function () {
var loc = location.href.match(/.*people\/alumni\/+/)[0],
url;
if ($(this).val() == 'reset') {
url = loc + '?no_cache=1';
} else {
url = loc + '?ts_address[year]=' + $(this).val() + '&no_cache=1';
}
sessionStorage.setItem("year", $(".year-filter select").first().val());
window.location.href = url;
});
}
My realurl config
'postVarSets' => array(
'_DEFAULT' => array(
'year' => array(
array(
'GETvar' => 'ts_address[year]',
),
),
),
)
Don't let urls being generated manually in frontend, like you do in Javascript.
My advice here would be to generate the urls backend side and attach it to a option attribute (data-reset-url, data-url).
// maybe a foreach here
$GLOBALS['TSFE']->cObj->typolink_URL([
'parameter' => '_PAGEUID_',
'additionalParams' => '?ts_address[year]=' . $year, // suppose in foreach have year var
'no_cache' => true
]);
If you think ext:realurl is the culprit deactivate ext:realurl and look if it works then.
I think it still will not work, but you will see something in the url that should give you the neccessary hint.
You probably stumble over a security feature of TYPO3: cHash.
With a cHash URL parameter TYPO3 secures it's URLs against injection of unrelated parameters for a cached version of a page. If TYPO3 builds an URL it hashes all parameters and appends this hash to the url. If such a cHash is found in an URL the parameters are fetched from database and all current URL parameters are ignored. especially any additional parameters. So the cached page matches the given url.
If you use ext:realurl, this cHash parameter is hidden in a 'normal' URL path. If you add parameters, like in your javascript, they are removed as they are not encoded in the cHash, which is encoded in the speaking URL.
In your case the additional parameter would change the content of the page. This page could be cached if the additional parameter is included in a cHash.
Here you must help realurl to either build an URL without cHash, or build URLs which contain these individual cHashes:
You could build a menu of available years and also configure a pathsegment for the year. In this way you can get individual cHashes for each year. You need to change your javascript to add a path-segment instead of a parameter.

Looking for general feedback on a URL-parsing script of mine (Javascript)

I'm fairly new to Javascript, and assembled the following (part is from an example online, rest is by me):
This works reliably, I'm just wondering how many best-practices I'm violating. If someone is nice enough to provide general feedback about the latter part of this script, that would be appreciated.
The two included functions are to (1) capture the incoming website visitor's referral data on a page, including URL query strings for analytics, and store it to a cookie. (2) When the visitor completes a form, the script will read the cookie's URL value, parse this URL into segments, and write the segment data to pre-existing hidden inputs on a form.
Example URL this would capture and parse: http://example.com/page?utm_source=google&utm_medium=abc&utm_campaign=name1&utm_adgroup=name2&utm_kw=example1&kw=example2&mt=a&mkwid=xyz&pcrid=1234
function storeRef() { //this function stores document.referrer to a cookie if the cookie is not already present
var isnew = readCookie('cookiename'); //set var via read-cookie function's output
if (isnew == null) {
var loc=document.referrer;
createCookie('cookiename',loc,0,'example.com'); //create cookie via function with name, value, days, domain
}
}
function printQuery() { //function to parse cookie value into segments
var ref=readCookie('cookiename'); //write cookie value to variable
var refElement = ref.split(/[?&]/); //create array with variable data, separated by & or ?. This is for domain info primarily.
var queryString = {}; //From http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
ref.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
//write segments to form field names below.
document.getElementsByName('example1')[0].value = refElement[0]; //exampleX is a form hidden input's name. I can not use getElementById here.
//need to be able to manually define these, which is why they aren't in a loop, though I'm not sure how to loop an array referenced in this way
document.getElementsByName('example2')[0].value = queryString['utm_source'];
document.getElementsByName('example3')[0].value = queryString['utm_medium'];
document.getElementsByName('example4')[0].value = queryString['utm_term'];
document.getElementsByName('example5')[0].value = queryString['utm_content'];
document.getElementsByName('example6')[0].value = queryString['utm_campaign'];
document.getElementsByName('example7')[0].value = queryString['utm_adgroup'];
document.getElementsByName('example8')[0].value = queryString['utm_kw'];
document.getElementsByName('example9')[0].value = queryString['kw'];
document.getElementsByName('example10')[0].value = queryString['mt'];
document.getElementsByName('example11')[0].value = queryString['mkwid'];
document.getElementsByName('example12')[0].value = queryString['pcrid'];
}
Thank you!
why would you need to use a cookie to store the data for that, if unless you wanna keep track of the visitors visiting to your site?

Django get last GET parameter

I've been working with Django for a few months now so I'm still new at it.
I want to get the last GET parameter from the URL. Here is and example of the URL:
example.com?q=Something&filter1=Test&filter1=New&filter2=Web&filter3=Mine
Is there a way to get the last inserted GET parameter with django? It could be filter1, filter2 or filter3..
Maybe there is a way to do this after the initial refresh with javascript/jQuery?
Thanks!
You can try to parse url parameters yourself. For example:
Python/Django
from urlparse import urlparse, parse_qsl
full_url = ''.join([request.path, '?', request.META['QUERY_STRING']])
#example.com?q=Something&filter1=Test&filter1=New&filter2=Web&filter3=Mine
parameters = parse_qsl(urlparse(full_url)[4])
#[(u'q', u'Something'), (u'filter1', u'Test'), (u'filter1', u'New'), (u'filter2', u'Web'), (u'filter3', u'Mine')]
last_parameter = parameters[-1]
#(u'filter3', u'Mine')
Javascript
var params = window.location.search.split("&");
//["?q=Something", "filter1=Test", "filter1=New", "filter2=Web", "filter3=Mine"]
var last_param = params[params.length-1].replace("?","").split("=");
//["filter3", "Mine"]
This example do not use jQuery and provides basic knowledge of url parsing. There are a lot of libraries, that can do it for you.

Passing an id value into a URL

My company hosts user created surveys on our server. When they are uploaded, they are given a key number as an identifier. I am trying to create a facebook app that people can post a simple survey to and distribute. I can set the canvas URL to the default URL of our server, but I need to pass that key to the query string at the end of the app URL.
<input type="hidden" id="SurveyKey" name="SurveyKey" value="130633791306">
so, the end link needs to be apps.facebook.com/myappname/130633791306
or apps.facebook.com/myappname/SurveyKey value
I am very new to JavaScript and didn't know if there was some get function that could just pull that from the source code and pass it into a new URL. I'm sure this is something easy, but as I am not sure how to word my question, my search result is coming up with a lot of unrelated material.
The URLs for our surveys look like this:
http://www.snapsurveys.com/swh/surveylogin.asp?k=130633791306
where k is a unique value for every survey. I want to be able to pull that value from the source code and pass it into the URL of my facebook app (which has the canvas URL set as our URL). So, it would look like apps.facebook.com/appname/k=VALUE_HERE
To get the query string in JavaScript you could use a code snipet like this:
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
Then you just define a variable to store the key, ie
var surveyKey = querySt("k");
Now you can use the surveyKey anywhere, so for example:
var url = "http://apps.facebook.com/appname/k=" + surveyKey;
http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml

Categories

Resources