I am developing a userscript that redirects insecure pages (HTTP) to the https: version.

// ==UserScript==
// @name         Secure Redirect
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  A simple userscript that redirects pages to https:.
// @author       You
// @match        *
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
        if (location.protocol != "https:") {
            window.location.href = "https:" + window.location.href.substring(window.location.protocol.length);

Please tell me if it works and what I can improve on. My GitHub repo for this project is here.

  • \$\begingroup\$ It would work but this is something that really should be done server side. \$\endgroup\$ Oct 1, 2018 at 1:24
  • \$\begingroup\$ "Please tell me if it works" - you should already believe that it works if you think the code is ready for Review! Any bug ought to be a real surprise... \$\endgroup\$ Oct 1, 2018 at 8:00
  • \$\begingroup\$ Um... this won't work. It'll redirect me from my file namespaces to an https version that doesn't exist. \$\endgroup\$ Oct 2, 2018 at 21:34

1 Answer 1



  • Pass global variables as parameters to IIFE to make your code more independent and clear
  • Use addEventListener method to follow recommended way of attaching event listeners Do you really need to execute redirection code, only when everything is loaded?
  • I would use regex to replace protocol to make solution robust
  • Try to not duplicate constant values (in this case protocol)

Suggested solution

(function (w) {
    'use strict';

    var secureProtocol = 'https';

    if ( !w.location.protocol.startsWith(secureProtocol) ) {
        w.location.href = w.location.href.replace(/^[^:]+/, secureProtocol);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.