JavaScript redirect based on domain name - javascript

I am not looking for a simple redirect.
What I am trying to do is this.
Person A loads site BOB.com and clicks a link to page X.
Person B loads site TIM.com and clicks a link to the same page X.
Page X has a javascript command on it that says, If user came from site Bob.com then redirect to Bob.com/hello.
If user came from TIM.com then redirect to Tim.com/hello.
If user didnt come from ether then redirect to Frank.com/opps.
This page X is going to handle 404 errors for multiple domains so it will need to ONLY look at the domain name upto ".com". It should ignore everything past the ".com".
This is the script I started with.
<script type='text/javascript'>
var d = new String(window.location.host);
var p = new String(window.location.pathname);
var u = "http://" + d + p;
if ((u.indexOf("bob.com") == -1) && (u.indexOf("tim.com") == -1))
{
u = u.replace(location.host,"bob.com/hello");
window.location = u;
}
</script>

Use document.referrer
if(/http:\/\/(www\.)?bob\.com/.test(document.referrer)) {
window.location = "http://bob.com/hello";
}
else if(/http:\/\/(www\.)?tim\.com/.test(document.referrer)) {
window.location = "http://tim.com/hello";
}
else {
window.location = "http://frank.com/oops";
}
Instead of the regex, you can use indexOf like you did initially, but that would also match thisisthewrongbob.com and thisisthewrongtim.com; the regex is more robust.

document.referrer is the place to be

Use document.referrer to find where the user came from.
The updated code is
<script type='text/javascript'>
var ref = document.referrer,
host = ref.split('/')[2],
regexp = /(www\.)?(bob|tim).com$/,
match = host.match(regexp);
if(ref && !regexp.test(location.host)) {
/* Redirect only if the user landed on this page clicking on a link and
if the user is not visiting from bob.com/tim.com */
if (match) {
ref = ref.replace("http://" + match.shift() +"/hello");
} else {
ref = 'http://frank.com/oops';
}
window.location = ref;
}
</script>
working example (it displays a message rather than redirecting)

Related

successively url redirection to page A or page B

I want to test the success of different styles of a landing page. I found a code which generates a redirection randomly to page A or page B. But I want to have it successively like on first pageload the user gets page A on second pageload page B and so on.
Here is the code for the random redirection. What do I need to change to get it successively?
var redirect, pageOptions = ['a.html', 'b.html'];
if (Math.random() < .5){
redirect = pageOptions[0];
} else {
redirect = pageOptions[1];
}
window.location.assign(redirect);
You can make use to localStorage which is builtin in major of the browser.
Here is the sample code:
var redirect, pageOptions = ['a.html', 'b.html'];
var getCount = parseInt(localStorage.getItem("redirectCount"));
if(getCount == null){
getCount = 0;
}
else{
getCount = (getCount+1)%2 ;
}
localStorage.setItem("redirectCount", getCount);
redirect = pageOptions[getCount];
window.location.assign(redirect);

Reload Parent Window without POST

I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.

If else statement for document.referrer

I require code for checking where a user has come from or change phone number?
JQuery i have is:
$(document).ready(function() {
var referrer = document.referrer;
});
I need an If Else Statement to see:
if (user is from (testsite1.com.au))
// run referrer
else
//change phone number to 0438 789 999
Please Help
UPDATED CODE SO FAR -----
$(document).ready(function() {
var referrer = document.referrer;
});
var site = 'http://www.tp1.websyte.com.au/';
if(site == true) {
alert('Came From .websyte site');
} else {
$(function(){
$('body *').replaceText( /\b03 9532 1600\b/gi, '0438 610 584' );
});
}
In order to check if a user came from your site we can use document.referrer, note that this only works when you are moving from one site to another by a link. It will not work if a user typed in a URL website directly.
To change phone numbers on the site is simple. We just look for our phone numbers decribed the the anumber class, cycle through them and change there html contents to the number you want.
var lastUrl = document.referrer;
if(lastUrl.search("websyte") == -1) {
$( ".anumber" ).each(function() {
$(this).html("0438765876");
});
}
This means that we first get the last url, call it lastUrl. Then if it had "websyte" somewhere in that url we assume that they came from your website. In that case it returns some positive number. If we didn't find it -1 is returned. Only when we didn't find "websyte" is when we cycle through all the anumber classes and change their html content to 0438765876.
Fiddle Here

Page refresh goes back to home page when using History.js in ie9 and below

I've built a site that uses the History.js plugin to navigate from page to page with AJAX and update the URL accordingly. All works well except in IE; when you refresh the page it essentially loads the content from the first page you came to, not the current pages content. In "decent" browsers it doesn't load the content from any page, it just loads the entire page for that URL, which is what I IE should do.
I'm thinking it doesn't understand what to do with the hash. If you visit http://www.crownacre.voyced.com/contact-us/ it works fine, but when you visit http://www.crownacre.voyced.com/#contact-us/ (with the hash) it doesn't.
I've attempted to redirect the page if it detects a # in the pathname, but there is no way of detecting this as window.location.pathname and History.getHash() returns the path without any hash.
Any suggestions? I've seen a few websites using this plugin that have the same problem, and similar issues on here, but no solution.
Thanks in advance!
I ran into the same problem in my rewrite of tarheelreader.org. I'm using History.js and it is working fine except for the refresh issue in IE8. This hack is working for me.
In my startup code that only runs on initial page load I do:
var url = window.location.href;
if (url.indexOf('#') > -1) {
// ie refresh hack
controller.stateChange();
}
where controller.stateChange() is the state change handler I use for all History changes.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
context = hist.data;
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
You can see all the code in main.js and controller.js at https://github.com/gbishop/TarHeelReaderTheme
Edit
Further exploration has lead to a case where History.js uses the initial URL instead of the root. This hack seems to handle that case.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
bar = window.location.href,
context = hist.data;
//console.log("State changed...", url, context);
if (url != bar && bar.indexOf('#') > -1) {
//console.log('bar = ', bar);
// I think we only get here in IE8
// hack for hash mode urls
var root = History.getRootUrl(),
hashIndex = bar.indexOf('#');
if (root != bar.slice(0, hashIndex)) {
// try to fix the url
url = root + bar.slice(hashIndex);
//console.log('new url =', url);
window.location.href = url;
}
}
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
This worked for me:
<script>
var url = new String(document.location);
if (url.indexOf("#") > -1) {
alert("There is a Hash in the path");
}
</script>
Edit:
function LocationTest()
{
var loc = window.location;
alert(loc.href);
alert(loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
alert(loc.href == loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
}
Sample Source: window.location explained
Maybe a solution:
Can you please try the History.js unofficial version 1.8a2 of my fork from:
https://github.com/andreasbernhard/history.js
...and give feedback? Thank you very much!

Dynamically modify the url using javascript

I would like to change the url of the page when the user select another page to visit. The url is dynamically replace the original one.
eg.
If user visit page 1 , the url will be book.html?page=1
If page 30 then book.html?page=30 and so on.
However, when I change the link using javascript, it falls into a infinite loop.
It seems I keep visit->change link ->visit ->change link->.... How to fix this problem?
eg. When the link change, don't access the page.
var currURL = $(location).attr('href');
var index = currURL.indexOf('?');
currURL = currURL.substring(0, index != -1 ? index : currURL.length);
// fall into loop
$(location).attr('href', currURL + '?page=' + pageNo);
You can do this pretty easily with just standard javascript.
if(location.href.indexOf('?') !== -1 && location.href.indexof('?page=') === -1)
{
var urlArray = location.href.split('?');
var newURL = urlArray[0] + "?page=" + urlArray[1];
location.href = newURL;
}

Categories