Userscript to redirect insecure pages to HTTPS 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';
    window.onload=()=&gt;{
        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.
Overview


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);
    }
})(window);