I'm developing a site that is heavily reliant on javascript for browser history manipulation and only uses one actual page file. I want the script to run a function whenever the user hits the base url of the site, but I'm not sure what method is appropriate. Figured I could make a quick comparison of the current window location, but what if the user types in www instead of http://, or none of them. Something tells me this should be really easy.
if (window.location.href == 'http://mysite.com') {
console.log('you hit the base url, yay');
myFunction();
}
It sounds like you want to isolate the path part of the URL.
function isHomePage() {
return window.location.pathname === '/' || window.location.pathname === '';
}
That should cover your bases, even if the URL is something like
https://www2.example.com:443/#hash
window.location.href always includes the protocol, so there's no issue if the user omits that when typing in the URL.
If by base url, you mean there is no path component or hash fragment, you can check for this as follows:
if (window.location.pathname==='/' && window.location.hash==="") {
console.log('you hit the base url, yay');
myFunction();
}
JavaScript can access the current URL in parts. For this URL:
http://mysite.com/example/index.html
window.location.protocol = "http"
window.location.host = "mysite.com"
window.location.pathname = "example/index.html"
Make it sure to use the host property
if (window.location.host === 'mysite.com') {
console.log('you hit the base url, yay');
myFunction();
}
Related
In my code, I'm assigning the following:
window.location.href = "www.example.com/test";
But when the page actually loads, the browser URL is www.example.com/test/www.example.com/test. I'm not appending anything to the URL, and I'm not sure how its appending the URL again.
I think you're missing the "http" or "https" part. Have you tried the following?
window.location.href = "https://www.example.com/test";
or
window.location.href = "http://www.example.com/test";
Because you forgot the protocol. If you omit the protocol, window.location.href thinks you are trying to access a folder with the name of www.example.com, relative to the page you are currently on.
window.location.href="http://www.example.com/test/" will ensure that you access the external website www.example.com.
Hope this helps! :)
Check the way you are constructing the url, sometimes we miss the host, or enter the incorrect path
A safe way to change the URl is by making changes in the exisiting URL
first get the existing URL by
let exisitingURl = window.location.href;
now manipulate this url, for eg
exisitingURL = exisitingURL.replace('/auth', '/gateway');
now go to the url by
window.location.href = existingURL;
function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.
Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)
You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}
If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.
In my code I'm trying to do something like this:
if (href = "http://hello.com")
{
whatever[0].click();
}
So the point is, I'm trying to get the script to click on a button only when the window is opened in a specific href.
window.location contains a number of interesting values:
hash ""
host "stackoverflow.com"
hostname "stackoverflow.com"
href "http://stackoverflow.com/questions/21942858/is-there-anything-like-a-if-href-command"
pathname "/questions/21942858/is-there-anything-like-a-if-href-command"
port ""
protocol "http:"
search ""
so, in your example, that would be:
if (window.location.hostname === "hello.com") {
}
Or, what you probably want to do since you know the domain, is use the pathname:
if (window.location.pathname === '/questions/21942858/is-there-anything-like-a-if-href-command') {
}
window.location.toString() returns the full URL (ie. what you see in your address bar):
>>> window.location.toString()
"http://stackoverflow.com/questions/21942858/is-there-anything-like-a-if-href-command/21942892?noredirect=1#comment33241527_21942892"
>>> window.location === 'http://stackoverflow.com/questions/21942858/is-there-anything-like-a-if-href-command/21942892?noredirect=1#comment33241527_21942892'
true
I've always avoided this, since 1) It breaks when you change protocols (http/https) 2) Breaks when you run your script on another domain. I would recommend using the pathname.
Also see MDN.
Bonus tip
Your example does this:
if (href = "http://hello.com")
You use ONE =, which is assignment, not comparison. You need to use == or === (this is a very common mistake, so be on the lookout for it!)
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.