Rewriting Links with Javascript - javascript

I have a few hyperlinks like this on my page
Link
When there is a query string in the address, example: mydomain.com?r=abcd the hyperlink should change to Link
I want the same thing to happen to "rh" query argument also. ie, when someone goes to mydomain.com?rh=abcd
This Link
should change to Link
Basically the script should say: if the queries "r" and "rh" is not null, the links with the class=rewrite must be changed. Everything after the "?" must be removed & the query string in the address should be added to the hyperlinks.

change the domain:
var newurl = 'http://testdomain.com';
$('a').each(function(I,EL){
var url = $(EL).attr('href');
if(url.indexOf('?')>= 0){
url = url.split('?');
url = newurl + url[1];
$(EL).attr('href', url);
}
}

Related

JavaScript: How to save the state of your website structure to a link (or hash link)

In my website I have some part when you 'click' on it, It will show a (pop-up) div & grays the rest of the website, However I want to make a link/hashlink for that state.. something like this ( http://www.mywebsite.com/show-pop-up ), So whenever my visitors type the link above in their browser and go, They will come to my website with (the pop-up visible).
I saw this in Trello.com & Behance.com (When you click in a project it will show as pop-up with a new link in the browser).
Note: I need this in 'pure' JavaScript.
There are several ways you can achieve this. One of the following options may work for you.
Option 1: using hashes. Consider the following url: www.mywebsite.com/index.html#popup. You can retrieve the #popup value on startup of your website and act accordingly. See the code sample below.
document.addEventListener("DOMContentLoaded", function(event) {
// Website has loaded.
var hash = location.hash
// Check if the hash exists and is popup.
if (hash && hash === 'popup') {
// Show your popup
}
});
Another option would be to use query strings. Consider the following url: www.mywebsite.com?popup=true. First you have to retrieve the query strings, using for example the following function. Afterwards check if the popup querystring has been used.
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, " "));
}
var popup = getParameterByName('popup');
// Check if we have the popup parameter.
if (popup) {
// Show popup
}
Suggest using
http://www.mywebsite.com#show-pop-up
instead of
http://www.mywebsite.com/show-pop-up
then using
if(location.hash === '#show-pop-up') {
// show your popup
}
on page loaded.

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'?

Will 'http:url' work for all browsers and devices?

In making a function that validates a user URL and prepends http: at the front, I have to take cases of www, https and // into account as being valid urls. The way I have it written now (see below), I only prepend http: , so that cases of //stackoverflow.com don't turn into http: ////stackoverflow.com.
This means that a url like stackoverflow.com becomes http:stackoverflow.com.
In Firefox and Chrome, this works just fine, but these URLS will be clicked from a variety of browsers and devices. Is it something that'll work universally? It'll be easy to rewrite this check for a // case, but I'm interested in the answer.
Prepend method:
function prependHTTPtoWebURL() {
var url = (el('org_website').value);
var httpVar;
var testFor;
if (url) {// If there's a website URL value
testFor = url.toLowerCase();
if (testFor.indexOf("http") != 0){
httpVar = 'http:'; //add it
url = httpVar + url;
el('org_website').value = url;
}
}
}
Try playing with regex. Check this code for instance:
var someurl = "www.google.com";
var otherurl = "google.com";
var anotherurl = "//google.com";
function prependHTTPtoWebURL(url) {
var newurl = url.replace(/^(http)?(:)?(\/\/)?/i,'');
return 'http://' + newurl;
}
console.log(prependHTTPtoWebURL(someurl));
console.log(prependHTTPtoWebURL(otherurl));
console.log(prependHTTPtoWebURL(anotherurl));
The ouput in console.log will be:
http://www.google.com
http://google.com
http://google.com
Since you are specifying a subdomain (www) on the first one, that is respected. It avoids ending with four diagonals, like http:////. If your url was something like :google.com, it would also fix it correctly.
You can see it live here: http://jsfiddle.net/zRBUj/
Edit: Adding the /i Kate mentioned.
Change http: to http://
See these links for more info:
Anatomy of a URL
How the web works

How can I modify this javascript to ignore any data within a query string?

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');

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