DEV Community

Cover image for Building a Simple URL Shortener With Just HTML and Javascript
Palash Bauri πŸ‘»
Palash Bauri πŸ‘»

Posted on • Updated on • Originally published at palash.tk

Building a Simple URL Shortener With Just HTML and Javascript

.

URL Shortener, you might have used one of them in your life such as bit.ly, goo.gl and much more. They are useful for shortening long URLs so that you can easily share them with your friends, family or co-workers.

You might be wondering how these things work? To understand how these things work, we need to take a closer look at an url shortener so we’ll be building a simple url shortener. With That Task, we’ll be learning some new things as well as understand how URL Shortener works.

Today, we'll be building a simple url shortener which does not need a database system to host yourself, instead, we'll use jsonstore.io, I'll be assuming that you already know some basic HTML & Javascript.

So without further talking, Let's Start Building. . .

Start with HTML Part :

we'll need only a text input box, a button, and a script tag to create our url shortener.

first create an HTML file called index.html, as there is only a need of two elements, a text input box, a button.

So Let's start adding our three main elements,

<html>
    <body>
        <input type="url" id="urlinput">
        <button onclick="shorturl()">Short The URL</button>
        <script src="main.js"></script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

As I shown in the above code, I've created a simple HTML file. Inside body tags, there're only three elements an input, a button and a script.

the first element is input where we well type/paste our long url, I gave it an id name urlinput so it would be easy to access it inside javascript.

Next element is a button, when we click this button our long url will be shortened as it has onclickfunction which will be executed when we click the button, inside the shorturl() function there will be commands necessary to shorten the url.

At the end we have a script called main.js where all our main javascript codes will be in, above mentioned shorturl() function will be also there.

So, for now, our HTML part is complete. so let's start writing some javascript

Start writing some Javascript :

As we shown above, we'll need some javascript to create our url shortener.

Step 0: as I mentioned at first we'll be using jsonstore.io to store information about our long url, we will need a jsonstore.io endpoint url to store data, Visit jsonstore.io, you'll see something like below

Jsonstore Screenshot

Under the text This Is Your Endpoint you can see a text box with long url such as,

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1
Enter fullscreen mode Exit fullscreen mode

click the purple COPY button.

So Now, let's start writing some javascript . . .

create a javascript file called main.js and start following below steps

first, we must keep the copied link a variable

var endpoint = "https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1";
Enter fullscreen mode Exit fullscreen mode

then we need to generate some random string so that we can create a link between the short url and the long url.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com

So, now well create a function called getrandom()

function getrandom(){
    var random_string = Math.random().toString(32).substring(2, 5) + Math.random().toString(32).substring(2, 5);
    return random_string()
}
Enter fullscreen mode Exit fullscreen mode

Don't worry, I'll help you understand the above code,

first, we initiated a function called getrandom than we initialized a variable called random_string and gave it a value.

Math is a built-in javascript object which allows us to perform mathematical tasks on numbers. first we called the random function from Math , Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

You Can Learn More About Math object from HERE

Then we transform the returned number to a string using toString() and we gave it an argument of 32 so that we get a proper string not a binary, hexadecimal or octal,

Then we use substring(2,5) as well to slice the string and maintain the size of the string, then again we follow the same procedure to get another chunk of a random string and finally we add both chunks of the string using +

and don't forget to add a return statement returning our random string.

Remember, this is not the only way to generate random strings you can also use the technic mentioned below to achieve the goal


function getrandom() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 5; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

Enter fullscreen mode Exit fullscreen mode

Now Return to index.html and add JQuery because it will be easy to achieve our goals with ease if we use JQuery.

add at the end of body tag but before the main.js script tag

now again return to main.js

let's Create a Function called geturl which will take the value from the input box verify it and return the value


function geturl(){
    var url = document.getElementById("urlinput").value;
    var protocol_ok = url.startsWith("http://") || url.startsWith("https://") || url.startsWith("ftp://");
    if(!protocol_ok){
        newurl = "http://"+url;
        return newurl;
        }else{
            return url;
        }
}
Enter fullscreen mode Exit fullscreen mode

in geturl function we first store the value of the input box in url variable. Then we check if url protocols are ok or not and if the protocol doesn't start with http:// , https:// or ftp:// we add http:// at the beginning of the url then return the url.

Now we will need another function to change the hash in the location bar, let's create

function genhash(){
    if (window.location.hash == ""){
        window.location.hash = getrandom();
    }
}
Enter fullscreen mode Exit fullscreen mode

At first, we check if the hash location is empty if it's empty we than add a random hash to the location bar.

Example: if our url is https://example.com/#abcd then the value of window.location.hash will be #abcd

Next, we'll work on our main function shorturl() , so let's go...

function shorturl(){
    var longurl = geturl();
    genhash();
    send_request(longurl);
}
Enter fullscreen mode Exit fullscreen mode

At first we store the long url in longurl variable then we add a random hash to the location bar so that we can use the url as the short url , then we call the send_request() with an argument longurl , in this function we send JSON request to jsonstore to store the long url with a link to short url , so now let's create the send_request() function.


function send_request(url) {
    this.url = url;
    $.ajax({
        'url': endpoint + "/" + window.location.hash.substr(1),
        'type': 'POST',
        'data': JSON.stringify(this.url),
        'dataType': 'json',
        'contentType': 'application/json; charset=utf-8'
})
}
Enter fullscreen mode Exit fullscreen mode

Here we use JQuery to send JSON request, we send the request to endpoint+"/" + our random string hash from the location bar
as an example,

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd
Enter fullscreen mode Exit fullscreen mode

so whenever we will send a get request to the above-mentioned url we'll get the long url as data

Important : add the send_request() function before the shorturl() function , otherwise it will not work

To Know More About JQuery's Ajax Function go HERE
To Know More About JSON, go HERE

now we will the code to GET the long url linked to the short url entered in the address bar

var hashh = window.location.hash.substr(1)

if (window.location.hash != "") {
    $.getJSON(endpoint + "/" + hashh, function (data) {
        data = data["result"];

        if (data != null) {
            window.location.href = data;
        }

    });

Enter fullscreen mode Exit fullscreen mode

then the above-mentioned code will be executed whenever we put the short url in the address bar (eg. https://shorturl.com/#abcd )

at first, we store the hash value from the url to the hashh variable.

Example: if our short url is https://shorted.com/#abcd , the value of hash will be #abcd

then we check if the hash location is empty or not, if not empty we send a get request to the address, endpoint + hashh

Example :

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd
Enter fullscreen mode Exit fullscreen mode

and as usual, if everything is okay we will get the long url from the data which is a JSON array data, from that we extract the result with data["result"].

value of data will be similar to this {"result":longurl,"ok":true} , where long url is the url you shortened

Our URL Shortener is Almost Complete! Copy-Paste a long url in the input box then click Short The URL button! Copy The Link from Address Bar, it's your short url!

Cheer Up Guys!

Some Useful Tricks

We can add a function to automatically copy the short url when a user clicked the Short The URL button Using libraries like SimpleCopy, or ClipboardJS to copy the short url which is currently in the location bar.

if using SimpleCopy We can add simplecopy(window.location.href); at the end of shorturl() function copy the short url whenever use shortens a url

This Simple Url shortener relies on third-party libs such as jsonstore so it would not be a good idea to shorten some confidential long url with it.

You can host the Whole Project in Github/Gitlab pages and set up a simple CNAME, that's it your brand new personal url shortener is ready, you can use any static site hosting service to host your url shortener.

You Can Find the full source code of the Project in GITHUB


That's it for today, That is my first technical guide article so I apologize for any mistakes,

if you find any problems, mistakes, let me know the comments below πŸ‘‡.


If You Like My Work (My Articles, Stories, Softwares, Researches and many more) Consider Buying Me A Coffee β˜• πŸ€—

Top comments (17)

Collapse
 
jhotterbeekx profile image
John Hotterbeekx

Thanks for sharing! I've never heard of jsonstore.io, seems like a great product to use for quick prototyping.

If I could give you some pointers on your code, try and be consistent in the naming conventions you are using on methods and variables. Right now it seems like you sometimes use snake casing, like protocol_ok and send_request, while most of the time you don't case at all, like genhash or getrandom. Imagine them all being like

let protocolOk;
sendRequest()
genHash();
getRandom();

or if you prefer snake casing:

let protocol_ok;
send_request()
gen_hash();
get_random();

This reads a lot easier right. Try and remember writing the code so it's easy to read for others, and you'll see your code becoming cleaner and cleaner.

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

Thank You, I'll keep these in mind

Collapse
 
gijovarghese profile image
Gijo Varghese

Great one. It's much easier to create your own URL shortener with Netlify. See my post: How to Create Your Own Private URL Shortener for Free

Collapse
 
jonasroessum profile image
Jonas RΓΈssum

Really? You pull jQuery in for an ajax request?

I would recommend to just use fetch instead, as it is build into most browsers. If you are concerned about browser compatibility, use a polyfill.

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

Ah, I'll look into it soon to make it better.
Thank You

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

For Sending Json Request, I created a function with XMLHttpRequest() (Code)

(Actually I have changed the storage provider so APIs are little different but understandable)

First, we open a new connection to your storage provider, then tell them that we are going to send json data.
Then create a JSON Object something like this {"l":<LONG_URL> , "s": <SHORT_URL_SLUG>} then send the json object to my JSONBOX endpoint (yes, I have switched to jsonbox from jsonstore).

Collapse
 
georgewl profile image
George WL • Edited

I'm curious why you're not using the more widely used const and let syntax tbh, it makes the code much clearer in my opinion and you have to worry less about scoping.

Also, have you tried the new Fetch API? It's much easier to work with than Ajax

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

Agree with you πŸ‘.
Actually I'm thinking of rewriting this article after my exams.

Collapse
 
rafaacioly profile image
Rafael Acioly

thank you and congratulations!
I'm also building a url shortner (with Go to study) and I did not know aboutjsonstore.io, here is the project; github.com/rafa-acioly/urlshor

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

I checked you repo. Great Idea!

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

Actually I have plans for rewriting this month. I hope it will be soon.

I have only used jQuery for sending and fetching json requests. Which could be easily converted to Vanilla, infact I didn't use jQuery for the production. Meanwhile You can check that out the source and find your answers

GitHub logo bauripalash / fossurl

Your Own Url Shortner Without any fancy server side processing and support for custom url , which can even be hosted on GitHub Pages

. .

🌐 Open fossurl.ml

What is Fossurl

Fossurl is an simple URL Shortener Which Can Be Hosted For Free in Github/Gitlab Pages or in Static Site Hosting Service and It doesn't need you to buy any server!

🎯 Goal

Implementing a Simple URL Shortner which can be used without need of any hardcore server side processing and can be hosted on Static Site Hostings such as GitHub/Gitlab Pages

πŸ’» Stack

  • HTML
  • CSS
  • JavaScript
  • Database : jsonbox.io (Previously , jsonstore was used but several downtimes forced me to switch to jsonbox)

πŸ› οΈ Features

  • It's fast
  • It doesn't require any hosting server
  • You can use it just by forking the repo and running a script

πŸ‘» Wanna Help Improve It?

Steps:

  • Fork This Repo
  • Clone On Your Device or Open in Gitpod
  • On Linux cd to src direcotory and on Windows do whatever it's neccesary to change directory to src
  • If you're on…
Collapse
 
tomakali profile image
David jeba

how to see the stats of the short url?
clicks, demographics, utm builder etc?

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

Not implemented yet!

Collapse
 
eduardo305 profile image
eduardo305

Great article. My only question is how do you guarantee the short url is unique with the getRandom function? How many unique urls do you think the algorithm can provide?

Collapse
 
bauripalash profile image
Palash Bauri πŸ‘»

It's just simple guide , I've not made it complex, to let beginners understand the code easily.

Here's the production code,

bauripalash / fossurl

Your Own Url Shortner Without any fancy server side processing and support for custom url , which can even be hosted on GitHub Pages

FossURL πŸ”—

An Easy to Use URL Shortner Without Needing a User to setup a fancy Server with PHP or NodeJs to work.

>Working Demo<

our old domain fossurl.palash.tk is no longer used , instead we use fossurl.ml

Current Version : 2.0 beta

🎯 Goal Of This Project

Implementing a Simple URL Shortner which can be used without need of any hardcore server side processing and can be hosted on Static Site Hostings like GitHub/Gitlab Pages

πŸ’» Technologies Used

  • Client Side
    1. HTML
    2. CSS
    3. JavaScript
      • jQuery
      • SimpleCopy
  • Server Side
    1. Database : jsonstore.io

TODOs:

  • Shorten via api [Work in Progress]

  • Add Custom URL Supoort [DONE]

⚠ Warning

Please Don't Use FossUrl to shorten any sensitive Information , important files or any other sensitive things which can create privacy issues for an individual or a company or an organisation.

Licence : MIT

Logo License : Creative Commons Attribution-ShareAlike 4.0 International License

Please Contribute 😊


If You Like My Work Consider

…
Collapse
 
leonorader profile image
Leonora Der

+1 for jsonstore.io! thanks a lot for the tip! :)