Set a Cookie based on url Parameter - javascript

I need to set a cookie whenever a user clicks through one of our affiliate links and lands on our site with "src=uni" in the URL. The URLs will look something like this:
http://www.myadmin.com?src=uni&utm_source=uni&utm_content=[publisher_ID]
Function to create cookie:
function SetCookie() {
var url = window.location.href;
if(url.indexOf('?src' + uni) = 1)
document.cookie="QueryCookie";
}
Can somebody help me by telling where I am going wrong in creating this Cookie based on query parameters?

A few things here:
function SetCookie() {
var url = window.location.search;
if(url.indexOf('?src=uni') !== -1)
document.cookie="src=uni";
}
1) Use location.search to narrow down your range, not necessary, but less room for error,
2) Use !== -1 to test the indexOf method. indexOf returns "-1" if it does not find a match. And "0" if it finds a match at the beginning of the string. The string is "zero indexed" which means the first character in the string is in position "0".
3) Add the equal sign = along with your parameter name: src=.
4) Also, use the string "uni" if that is what you're looking for, rather than a variable named uni. If "src" can be a variety of values, then we'll need to add some more logic to account for that.
5) And when assigning to document.cookie use key/value pairs as in: key=value.

First thing you need to fix is:
if(url.indexOf('?src' + uni) = 1)
should be (this checks that it exists at index 1):
if(url.indexOf('?src=' + uni) === 1)
or (this checks it exists at all)
if(url.indexOf('?src=' + uni) !== -1)
Next, you need to set src to the uni and make it accessible to the entire site:
document.cookie="src="+uni+"; path=/; domain=.myadmin.com";
Adding the path=/ and domain=.myadmin.com will allow you to access the cookie at all paths on that domain, and the domain part lets it be accessible on all subdomains (i.e. www.myadmin.com as well as blog.myadmin.com, etc)
so all together:
function SetCookie() {
var url = window.location.href;
if(url.indexOf('?src='+uni) !== -1)
document.cookie="src="+uni+"; path=/; domain=.myadmin.com";
}
Here is some basic info:
http://www.w3schools.com/js/js_cookies.asp
Or the more in depth, accurate documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Related

Checking for a specific URL regex

I need to check for a specific URL pattern using regex and not sure what would be the approach but I think it should not be too complex for this case and therefore regex would be the preferred solution. I just need to check that the exact strings #, shares and assets are in the appropriate slots, for example:
http://some-domain.com/#/shares/a454-rte3-445f-4543/assets
Everything in the URL can be variable (protocol, domain, port, share id) except the exact strings I'm looking for and the slots (slash positions) at which they appear.
Thanks for your help!
You can use
/^https?:\/\/some-domain\.com\/#\/shares\/[^/]+\/assets/i
let url = `http://some-domain.com/#/shares/a454-rte3-445f-4543/assets`
let matched = /^https?:\/\/some-domain\.com\/#\/shares\/[^/]+\/assets/i.test(url)
console.log(matched)
Decided to avoid regex and do it this way instead.
const urlParts = window.location.href.split('/');
if (urlParts[3] === '#' && urlParts[4] === 'shares' && urlParts[6] === 'assets') {
// code goes here...
}

Updating a URL by adding a value of 1

So let's say the URL I have is
"mywebsite.com/file/100/"
What I want is for it to be updated to
"mywebsite.com/file/101/"
"mywebsite.com/file/102/"
(and so on...)
when the keyword cannot be found.
init();
function init()
{
searchWord("key word");
}
function searchWord(word)
{
var pageResults = document.body.innerHTML.match(word);
if(pageResults)
{
alert("word found");
} else {
}
}
Right now my script searches for a key term, and what I need is for the page to be updated by a value of 1 (100 to 101 to 102 etc) when the keyword cannot be found.
I am a noob a Javascript, none of this code is mine. I just need help developing it. I have searched around for a while, but I can't find much.
Thanks.
Not sure if this gets points for elegance.
Split the url into segments
Dispose of empty segment caused by trailing "/" if present.
If the last segment is numeric, replace it with its numeric value + 1.
Join the segments back into a string.
(If you want the trailing slash you can re-add it.)
Code
var url = "mywebsite.com/file/100/"
var segments = url.split("/");
while(segments[segments.length-1]==""){
segments.pop();
}
var lastSegment = segments[segments.length-1];
if(!isNaN(lastSegment)){
segments[segments.length-1] = (parseInt(lastSegment)+1).toString();
}
updatedUrl = segments.join("/");
One liner just for fun.
var url = window.location.hostname + window.location.pathname.split('/').map(function(sgmt){return (sgmt != '' && !isNaN(sgmt)) ? parseInt(sgmt)+1 : sgmt}).join('/');
You may want to omit the window.location.hostname to use relative url paths instead. The next piece first splits the url at the / and then uses the .map() method on the new array. The function that gets passed looks for non-blank and numerical sections of the url. If it finds it, it adds 1. When finished, it makes the array a string again (with the new number in the url) using the .join() method.

Finding out generalize method to get site name from it's website using Jquery

I'm trying to get any site's name(just a domain name without any sub domain name) to use in my chrome extension using JQuery. I'm able to find it in most of the cases. but i'm failing in few corner cases. Here is what i have done till now.
host_url = window.location.hostname;
This gives me only host name stripping page url, slug or params
https://ap2.salesforce.com/_ui/core/chatter/ui/ChatterPage ->
ap2.salesforce.com
http://go.sap.com/support.html -> go.sap.com
http://www.beaf.com/ -> beaf.com
http://www.digitalclicks.co.uk -> digitalclicks.co.uk
but how can I get to only domain name, because to remove sub-domain i can get split it and get the 2nd element which will give me salesforce, sap, beaf
if (full_domain.split(".").length > 2){
domain_name = full_domain.split(".")[1]; // handle the subdomain ie. http://go.sap.com
}else{
domain_name = full_domain.split(".")[0]; //for no subdomain www.beaf.com
}
But I'm failing for digitalclicks.co.uk,because here domain name is first. I have to find a generalize approach to solve this.
And how can I do this for all Top Level Domains??
Extract domain name from any url.
http://www.domain-name.co.uk/sub1/sub2/...
This is how it works:
step: it gets rid of http(s)://
step: it gets rid of everything behind "/"
creats an array splitted by "."
cuts the length of the array to 3 to get rid of "uk" in ".co.uk" f.e.
reverse the array because the domainname has to be [1] then. You have to do this, because the url could be like domainname.com(without subdomain)
edit:
In line 1 we need to add this + "/" in case there is no slash in the url.But we need a slash in the next step to get the substring.
function getDomainName(url) {
var _x = url.replace(/\w+:\s?\/\//.exec(url), "") + "/";
var __x = _x.substring(0, _x.indexOf("/"));
var __xRev = __x.split(".");
if (__xRev.length > 3) {
__xRev.pop();
}
__xRev.reverse();
return __xRev[1]; // <-- __xRev[1] is the domainname
}
document.write(getDomainName(prompt("please enter url")));

how do i append a cookie to the end of a src within an iFrame woithout an id?

So I wrote some cookies, but I need to append the information to the end of the src in an iframe. The problem is I can't figure out how to select the iframe because it doesn't have an id.
The iframe looks like this:
<iframe src="www.mysite.com";>
I need it to look like:
<iframe src="www.mysite.com&cookie";>
However I can not use an id to select the iframe because I am not the one creating the iframe and if there are iframes on other pages they need to be selected too and updated in the same way. So the function needs to be universal. If you want to see my code for the cookies I can also show you that.
If this is too vague let me know and I'll update it.
Here is a fiddle of what I think I am trying to do.
http://jsfiddle.net/Inzblaze/2h6ke9vg/3/
You need to append something to EVERY iframe src?
var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].src += 'something';
}
Will the src attribute always be the same? You could select it by:
var frame = $("iframe[src='www.mysite.com']");
Edit:
Here is how you can get and append the cookie:
Document.cookie will return the entire cookie as a string, and I am guessing you probably only want a certain value from that cookie. So you could do something like:
// This is just declaring a function that you can use to get cookie values.
function getCookie(cookieName) {
// If you open up your console and type in document.cookie, you will see
// that all cookie values are inside of this same string. So this
// function will allow you to extract the value you are looking for
// We start by creating a new Regular Expression object, that will
// be used to match a certain pattern of text.
var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
// This line actually uses our pattern, and returns the match from
// the cookie.
var sMatch = (' '+document.cookie).match(re);
// if we have a cookie name, and our regular expression found a match
// in the cookie, then return the value that was found from the match
if (cookieName && sMatch) {
return unescape(sMatch[1]);
}
// if we dont find a matching value, just return an empty string
return '';
}
Which allows you to do something like:
// Now we are actually CALLING our function, and pass in whatever we named
// our cookie value. The variable cookieValue will then hold this value.
var cookieValue = getCookie("cookieName");
// Here we are using jQuery to find the iframe element we want to manipulate
// and save reference to it in a variable called 'frame'
var frame = $("iframe[src='www.mysite.com']");
// From this element, we grab it's current src value
var currentSrc = frame.attr("src");
// here, we SET the frames src value, by setting it back to it's current src
// and tack on the cookie value
frame.attr("src", currentSrc + "&" + cookieValue);

Remove querystring parameters from url with regex

I'm pretty new to regex and need to remove some content from our url
http://mysite.blah/problem/smtp/smtp-open-relay?page=prob_detail&showlogin=1&action=smtp:134.184.90.18
I need to remove everything from the "?" and on, leaving me just:
http://mysite.blah/problem/smtp/smtp-open-relay
Here is our current regex expression we are using to grab the route data. For example I can grab "smtp" and "smtp-open-relay" (which we need). However sometimes our url changes depending on where the user is coming from thereby appending the querystring parameters which is causing our current regex expression to blow up.
// Retrieve the route data from the route
var routeData = /([0-9a-zA-Z_.-]+)\/([0-9a-zA-Z_.-]+)$/g.exec(route);
I need it to ignore stuff from the "?" on.
A regular expression is probably more than you need.
You could do the following to remove the ? and everything (query
string + hash) after it:
var routeData = route.split("?")[0];
If you truly wanted to strip only the query string, you could preserve
the hash by reconstructing the URL from the window.location object:
var routeData = window.location.origin + window.location.pathname + window.location.hash;
If you want the query string, you can read it with window.location.search.
i just used this one
var routeData= route.substring(0, route.indexOf('?'));
Use this function:
var getCleanUrl = function(url) {
return url.replace(/#.*$/, '').replace(/\?.*$/, '');
};
// get rid of hash and params
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
If you're doing this in-browser, let the browser do the parsing:
location.origin + location.pathname
Or for arbitrary URLs:
function withoutQS(_url) {
var url = document.createElement('a');
url.href = _url;
return url.origin + url.pathname;
}
Following is the cleaner way to remove a given parameter say: prop1 form querystring of url.
Querystring can be found in url by accessing
window.location.search
Here you apply regular expression for prop1:
var queryStringWithoutProp1=window.location.search.replace(/(&?prop1=)(.[^&]*)/,"");
queryStringWithoutProp1 must return querystring without prop1=value parameter-value combination from querystring
Note: '&?' ensures whether prop1 appears as first parameter or any subsequent one.

Categories