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!)