GetGimphed
GetGimphed

Reputation: 45

Difference in window.location.protocol and window.isSecureContext?

In JavaScript you can check whether the url/website accessed is over Http or Https, via 2 ways

  1. window.location.protocol which returns http: or https:

  2. window.isSecureContext which returns true for https and false for http.

I know that window.isSecureContext is non-standardised. But lets say I know it is available at the client browser.

Then,

  1. what is the difference between the two read-only values? Which one to use?
  2. Most Importantly, In which case would there be an anomaly. Meaning, first method says https: while second says false or other way around.

Upvotes: 3

Views: 1828

Answers (2)

Marsou001
Marsou001

Reputation: 87

window.location.protocol 

returns a string containing the protocol of the website you are browsing at the moment. it could be "https", "http", "file" for local HTML files...

It does mean that it is secure.

isSecureContext

on the other hand, returns a boolean, true if it is secure, or false if it isn't.

Take for example a simple static HTML page with "file" protocol. If you type into the console "isSecureContext", it will return true. A locally served web app "localhost" will return true too, although these last two are not served on an "https" protocol.

So yes. The two options are indeed different from each other.

Upvotes: 1

jcaron
jcaron

Reputation: 17720

From https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts :

A context will be considered secure when it's delivered securely (or locally), and when it cannot be used to provide access to secure APIs to a context that is not secure. In practice this means that for a page to have a secure context, it and all the pages along its parent and opener chain must have been delivered securely.

For example, a page delivered securely over TLS is not considered a secure context if it has a parent or ancestor document that was not delivered securely, since otherwise the page would then be able to expose sensitive APIs to the non-securely delivered ancestor via postMessage messages. Similarly, if a TLS delivered document is opened in a new window by an insecure context without noopener being specified then the opened window is not considered to be a secure context (since the opener and opened window could communicate via postMessage).

Locally delivered files such as http://localhost and file:// paths are considered to have been delivered securely.

(Emphasis mine)

Upvotes: 2

Related Questions