How can I add something in JavaScript that will check the web site URL of someone on a web site and then redirect to a certain page on the web site, if a match is found? For example...
The string we want to check for, will be mydirectory, so if someone went to example.com/mydirectory/anyfile.php or even example.com/mydirectory/index.php, JavaScript would then redirect their page / url to example.com/index.php because it has mydirectory in the url, otherwise if no match is found, don't redirect, I'm using the code below:
var search2 = 'mydirectory';
var redirect2 = 'http://example.com/index.php'
if (document.URL.substr(search2) !== -1)
document.location = redirect2
The problem with that, is that it always redirects for me even though there is no match found, does anyone know what's going wrong and is there a faster / better way of doing this?
Use String.indexOf() instead:
if (window.location.pathname.indexOf('searchTerm') !== -1) {
// a match was found, redirect to your new url
window.location.href = newUrl;
}
substr is not what you need in this situation, it extracts substrings out of a string. Instead use indexOf:
if(window.location.pathname.indexOf(search2) !== -1) {
window.location = redirect2;
}
If possible it's better to do this redirect on the server side. It will always work, be more search engine friendly and faster. If your users have JavaScript disabled, they won't get redirected.
Related
I have this code :
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val());
window.location = "http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val();
}
In the console I have
http://myWebsite.dev/dailyGift?id_event=41?week_id=44?year_id=2016.
When I access directly works without problems, but jQuery does not make this redirect and I don't understand where is the problem.
You need to change all the ? with & except the first one
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'&week_id='+$('#week_id').val()+'&year_id='+$('#year_id').val());
}
Please replace all "?" with "&", Correct URL would be :-
http://myWebsite.dev/dailyGift?id_event=41&week_id=44&year_id=2016
Also it would be good if you encrypt ids for security purpose.
You say that you want to redirect to a link but you're merely changing the location.href value which is equivalent to clicking a link.
Location.replace() will load the new resource in place of the current one. The current page will not be added to the session history so it will not be possible to return to it using the back button.
I've also cleaned up the use of " and ' in the url string to make it cleaner.
if ($('#category').val() == 4){
var url = "http://"+window.location.hostname+"/dailyGift?id_event="+$('#sub-category').val()+"&week_id="+$('#week_id').val()+"&year_id="+$('#year_id').val();
console.log(url);
window.location.replace(url);
}
I'm currently using this JavaScript popup confirmation redirect:
var answer = confirm("If you are joining us through site other than" +
"website.net, .com or .info please hit OK otherwise hit cancel!");
if(answer)
window.open('http://website.net', '_blank');
else
alert("You need to know that it will not work for you well if you don't")
I would really like a way to use this popup only if user was not on targeted page.
I think this is what you're trying to do:
var domains = ["aseanlegacy.net", "aseanlegacy.com", "aseanlegacy.info"];
if(domains.indexOf(document.location.hostname) == -1)
window.open("http://aseanlegacy.net", "_blank");
If the user is at a domain not in domains (tested with document.location.hostname), window.open will be called.
Here's a JSFiddle.
Per your request to only open the window once per session, here is the code modified to include a cookie:
var domains = ["aseanlegacy.net", "aseanlegacy.com", "aseanlegacy.info"];
if(domains.indexOf(document.location.hostname) == -1 && document.cookie.indexOf("opened=1") == -1)
{
document.cookie = "opened=1";
window.open("http://aseanlegacy.net", "_blank");
}
Here's the updated JSFiddle.
It is quite unclear what you want to achieve, but you can grab the "referrer" using:
document.referrer
Which will tell you where the user came from. I base this on your quote:
If you are joining us through site other than aseanlegacy.net...
I have absolute no idea why this would matter, and why you tell the user the website will not work well otherwise.
If you want to get the current location, simply use:
document.location.href
which returns the full URL, or
document.location.hostname
which returns the hostname.
I am trying to implement what seems to be very simple JavaScript redirection, via the following rudimentary command:
window.location.href = "http://www.somesite.com";
So far so good, it works. I also can do it via the following method:
location.replace("http://www.somesite.com");
No problem here, it works again! The problem comes when I loose the protocol out of the string:
window.location.href = "www.somesite.com";
OR:
location.replace("www.somesite.com");
It just appends the new location to the current url:
www.currentsite.com/www.somesite.com
Of cause, that's not what I want. Is there any way to force the redirect?
One way is to use protocol-relative url like this:
window.location = "//www.somesite.com";
Or
window.location = "//somesite.com";
This way, it would redirect and browser itself will take care of figuring out protocol part eg http or https
Working Example
The protocol is required.
How else would the browser know whether
location.replace("mysite.pl");
was going to a Polish website or a Perl script on the current website?
You could do something like this to add http:// to the URL if it's not already there... although I can't think of a reason for not just including it yourself. Why complicate things?
function redirect(url) {
if(url.substr(4) != "http")
url = "http://" + url;
window.location.href = url;
}
redirect("www.google.com")
I have the below JavaScript, and when the url (window.location) does not contain www. the javascript IS executed
var windowloc = window.location; // http://mywebsite.com/
var homeurl = "http://mywebsite.com/";
if(windowloc==homeurl){
//JavaScript IS EXECUTED
}
and if it does the javascript is not executed.
var windowloc = window.location; // http://www.mywebsite.com/
var homeurl = "http://mywebsite.com/";
if(windowloc==homeurl){
//JavaScript is NOT executed.
}
How can I overcome this by allowing the JavaScript to accept urls (window.location) with and without www.
Use code like this see if the domain has www.mywebsite.com in it:
if (window.location.href.indexOf("//www.mywebsite.com/") != -1) {
// code to execute if it is www.mywebsite.com
} else {
// code to execute if it is not www.mywebsite.com
}
or, you could use just the hostname part of window.location like this to just check for the "www.":
if (window.location.hostname.indexOf("www.") != -1) {
// code to execute if it is www. something
} else {
// code to execute if it is not www. something
}
or if you wanted to check for exactly your entire domain, you could do it like this:
if (window.location.hostname === "www.mywebsite.com" {
// code to execute if it is www.mywebsite.com
} else {
// code to execute if it is not www.mywebsite.com
}
You can overcome that using regex, as I am sure other answers will provide. However, it's best practice for search engine optimization (SEO) to force your http://mywebsite.com/ to do a perminant redirect to http://www.mywebsite.com/ because search engines like Google consider the www. and www-less versions two separate websites.
Then you will not need two separate conditions because your url will always be the www. version.
if (window.location.href.indexOf("://www") === -1) {
// "www" excluded
} else {
// other stuff
}
edited the code sample to be more specific
if(window.location.href.indexOf('mywebsite.com')!= -1){
//do stuff
}
Use the hostname property of the location object to determine what address you're being served under:
if (location.hostname==='mywebsite.com')
// do something
location and other address-owning objects like links have properties like hostname, pathname, search and hash to give you the already-parsed pieces of the URL, so you don't have to try to pick apart URL strings yourself. Don't just look for the presence of www. in the location string as it might be somewhere else in the string that isn't the hostname.
But +1 Justin's answer: if you are trying to redirect alternative addresses such as a non-www address to a canonical address, the right way to do that is with an HTTP 301 redirect and not anything to do with JavaScript. This would normally be configured at the server level, eg for Apache you might use a Redirect in your .htaccess.
My goal is to redirect my website to (/2012/index.php)
ONLY IF the user goes to ( http://www.neonblackmag.com )
ELSE IF
the user goes to ( http://neonblackmag.com.s73231.gridserver.com ) they will not be re-directed... ( this way i can still work on my website and view it from this url ( the temp url )
I have tried the following script and variations, i have been unsuccessful in getting this to work thus far....
<script language="javascript">
if (document.URL.match("http://www.neonblackmag.com/")); {
location.replace("http://www.neonblackmag.com/2012"); }
</script>
This should work:
<script type="text/javascript">
if(location.href.match(/www.neonblackmag.com/)){
location.replace("http://www.neonblackmag.com/2012");
}
</script>
You should use regular expression as an argument of match (if you're not using https you can drop match for http://...
In your solution the semicolon after if should be removed - and I think that's it, mine is using location.href instead of document.URL.
You can also match subfolders using location.href.match(/www.neonblackmag.com\/subfolder/) etc
Cheers
G.
document.url doesn't appear to be settable, afaict. You probably want window.location
<script type="text/javascript">
if (window.location.hostname === "www.neonblackmag.com") {
window.location.pathname = '/2012';
}
</script>
(Don't use language="javascript". It's deprecated.)
Anyone at any time can disable JavaScript and continue viewing your site. There are better ways to do this, mostly on the server side.
To directly answer your questions, this code will do what you want. Here's a fiddle for it.
var the_url = window.location.href;
document.write(the_url);
// This is our pretend URL
// Remove this next line in production
var the_url = 'http://www.neonblackmag.com/';
if (the_url.indexOf('http://www.neonblackmag.com/') !== -1)
window.location.href = 'http://www.neonblackmag.com/2012/index.php';
else
alert('Welcome');
As I said, this can be easily bypassed. It'd be enough to stop a person who can check email and do basic Google searches.
On the server side is where you really have power. In your PHP code you can limit requests to only coming from your IP, or only any other variable factor, and no one can get in. If you don't like the request, send them somewhere else instead of giving them the page.
header('Location: /2012/index.php'); // PHP code for a redirect
There are plenty of other ways to do it, but this is one of the simpler. Others include, redirecting the entire domain, or creating a test sub domain and only allow requests to that.