javascriptsecuritysecure-context

check if page is served securely over https


I am creating a chrome extension that exposes extra APIs to websites. Before these APIs can be used by websites, I want to show a warning if the website was served over HTTP and not HTTPS. This is because these APIs reduce the web sandbox and could be more dangerous if the JavaScript source from the website is not verified to have come from the correct party.

Is there a reliable method I can use to check if a website was served over HTTPS?
Maybe a chrome extension API (for example inside a content script)?

Checking location.protocol seems to be potentially inaccurate in case of problems with the certificate: How do I determine whether a page is secure via JavaScript?


Solution

  • For newer browsers:

    window.isSecureContext
    

    You can also:

    window.location.protocol == 'https:'
    

    However, this may be wrong if the webpage protocol is https but the certificate was invalid and the webpage proceeded to load in a non-secure context.