I want to know if the page is being accessed via http or https using JavaScript. Is there some sort of isSecure() method, or should I just parse it out of the URL somehow?
Asked
Active
Viewed 3.8k times
3 Answers
121
location.protocol
should do it for you.
(as in:
if (location.protocol === 'https:') {
// page is secure
}
)

Peter Stone
- 3,756
- 4
- 23
- 14
-
This seems to cover the main page, what about all the additional loads (Google Analytics, Ads, external images, javascript, etc?) – Thomas BDX Mar 07 '16 at 18:28
-
Do not rely on this! As a demo visit https://macinn.es/ and dismiss any warnings about the site not being secure, then open a console and run `location.protocol`. It returns "https:" even though the browser has just told you that it's not secure. – Nathan MacInnes Mar 15 '17 at 16:13
-
3@NathanMacInnes OP may want certain scripts from his server to run in the client browser iff the connection is https. It does not give you much credibility when you say "don't rely on this", and then fail to suggest a better method. I seriously wish that people on stack would refrain from posting all these type of comments. It's not helpful. – theAnonymous Mar 25 '18 at 06:43
-
1@user3635998, "do not rely on this" was a little melodramatic of me, but it's still a valid caveat. – Nathan MacInnes Apr 12 '18 at 19:19
10
You should be able to check document.location.protocol
to see if it's "http:" or "https:"

Marc Novakowski
- 44,628
- 11
- 58
- 63
2
While location.protocol should do it for you as Peter Stone mentioned, but you shouldn't rely on Javascript for any true security, etc.
I think the value with be "https:" for location.protocol if you are on SSL.

Jason Jackson
- 17,016
- 8
- 49
- 74
-
1Yeah, if you need SSL for security, check server-side (Apache sets the HTTPS environment variable if SSL is in use). If you just need to know which it is (i.e., use secure Google Analytics to avoid "partial security" warnings), this will be okay. – Peter Stone Jan 05 '09 at 23:13
-
2I just need to know which it is to avoid the "non-secure elements warnings in IE". It's a stopgap measure until our next release. – braveterry Jan 05 '09 at 23:27