Some Useful tiny JavaScript functions

Force HTTPS in JavaScript

We can use JavaScript to check if the users are on a secure (HTTPS) page and redirect them to the HTTPS equivalent of the current page if they are not on one, at the moment.

toHttps: function() {
    if (window.location.href.indexOf("https://") === -1) {
        window.location = "https://" + window.location.hostname +
        window.location.pathname +
            window.location.search +
        window.location.hash;

    }
},

HTML characters and security

As JavaScript does not have a built-in function which performs the task of PHP’s htmlentitiesor htmlspecialchars we can easily build one. However, we do not want to convert all HTML special characters to their equivalent entities or vice-versa. We just want to convert enough of them to prevent users from adding scripts and other possibly malicious tags and attributes through their input.

To convert the special characters in HTML to harmless entities we can just use multiple global replaces:

toEntities: function(string) {
    return string.replace(//g, ">").
        replace(/"/g, """).replace(/&/g, "&");
},

Doing the opposite just requires you to replace the entities to special characters:

Parse query string with JavaScript

Another useful thing that you are probably aware of is parsing the GET parameters in the URL. You know that you can access them with window.location.search but the value returned is just a string with raw parameters that you have to parse, something like this: “?a=1&d&bb=355&grr=hello”. Therefore, we can create a small function which will take any URL as an argument and convert the GET parameters into an object that can easily be used within the application.

usefull javascript

Break your website out of iframes

To exemplify, if in index.html we call the escapeFrames method:

Conclusion

It is a good idea to place the functions that you frequently use in your projects in a separate file and reuse them over and over again whenever they are needed. That way after some time passes you will have built a collection of many functions which you can easily reuse in different projects without starting from scratch every time.

You can download the usefulStuff library and a file with some examples.

Published by

Smart Web Care

Smart Web Care offers a wide range of IT Solutions ranging from Website Development, E-Commerce Solutions, Multimedia, Brand Promotions, Graphic design, Domain Registration, Android/iOS App developer,Web Designer, Software Application Company, Web hosting company, IT support and services, Internet Marketing Service, Marketing Consultant Servers, Web Hosting and Tanning provider.