如何仅使用HTML和JavaScript构建简单的URL缩短器

by Palash Bauri

由Palash Bauri

如何仅使用HTML和JavaScript构建简单的URL缩短器 (How to build a simple URL shortener with just HTML and JavaScript)

You might have used a URL shortener before, such as bit.ly, goo.gl. They are useful for shortening long URLs so that you can easily share them with your friends, family or co-workers.

您可能以前使用过URL缩短器,例如bit.lygoo.gl 。 它们对于缩短长URL很有用,以便您可以轻松地与朋友,家人或同事共享它们。

You might be wondering how these things work. To understand how, we need to take a closer look at an URL shortener — so we’ll be building a simple one! With that task, we’ll be learning some new things as well as understanding how a URL shortener works.

您可能想知道这些事情如何工作。 要了解操作方法,我们需要仔细研究URL缩短器-因此我们将构建一个简单的URL缩短器! 通过该任务,我们将学习一些新知识,并了解URL缩短器的工作原理。

Today, we’ll be building a simple URL shortener which does not need a database system to host it. Instead, we’ll use jsonstore.io. I’ll be assuming that you already know some basic HTML & JavaScript.

今天,我们将构建一个简单的URL缩短器,它不需要数据库系统来托管它。 相反,我们将使用jsonstore.io 。 我假设您已经了解一些基本HTML和JavaScript。

So without further ado, let’s start building. . .

因此,事不宜迟,让我们开始构建。 。 。

从HTML开始 (Start with the HTML)

We’ll need only a text input box, a button, and a script tag to create our URL shortener.

我们只需要一个文本输入框,一个按钮和一个脚本标签即可创建我们的URL缩短器。

First create an HTML file called index.html, as there is only a need for those two elements (a text input box and a button).

首先创建一个名为index.htmlHTML文件,因为只需要这两个元素(一个文本输入框和一个按钮)。

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>

As I showed you in the above code, I’ve created a simple HTML file. Inside the body tags, there are only three elements: an input, a button and a script.

正如我在上面的代码中向您展示的那样,我已经创建了一个简单HTML文件。 在body标签内部,只有三个元素: inputbuttonscript

The first element is input where we will type/paste our long URL. I gave it an id name urlinput so it would be easy to access in the JavaScript.

第一个元素是input ,我们将在其中输入/粘贴长网址。 我给它指定了一个id名称urlinput因此可以很容易地在JavaScript中进行访问。

The next element is a button. When we click this button, our long URL will be shortened as it has an onclick function which will be executed when we click the button. And inside the shorturl() function there will be commands necessary to shorten the URL.

下一个元素是一个button 。 当我们单击此按钮时,我们的长URL将被缩短,因为它具有onclick函数,该函数将在我们单击按钮时执行。 在shorturl()函数内部,将存在一些必要的命令来缩短URL。

At the end we have a script called main.js where all our main JavaScript code will be. The above-mentioned shorturl() function will be also there.

最后,我们有一个名为main.jsscript ,其中所有主要JavaScript代码都在其中。 上面提到的shorturl()函数也在那里。

So, for now, our HTML part is complete. Let’s start writing some JavaScript

因此,到目前为止,我们HTML部分已经完成。 让我们开始编写一些JavaScript

开始编写一些JavaScript (Start writing some JavaScript)

As we showed above, we’ll need some JavaScript to create our URL shortener.

如上所示,我们需要一些JavaScript来创建URL缩短器。

Step 0: as I mentioned, we’ll be using jsonstore.io to store information about our long URL. We will need a jsonstore.io endpoint URL to store data, so you can visit jsonstore.io where you’ll see something like below:

步骤0:正如我提到的,我们将使用jsonstore.io存储有关我们的长URL的信息。 我们将需要一个jsonstore.io 终结点 URL来存储数据,因此您可以访问jsonstore.io ,在其中您将看到以下内容:

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

在文本“ 这是您的端点”下 ,您可以看到一个带有长URL的文本框,例如:

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1

Click the purple COPY button.

单击紫色的“ 复制”按钮。

So now, let’s start writing some JavaScript . . .

现在,让我们开始编写一些JavaScript。 。 。

Create a JavaScript file called main.js and start following the below steps.

创建一个名为main.jsJavaScript文件,然后开始执行以下步骤。

First, we must keep the copied link as a variable:

首先,我们必须将复制的链接保留为变量:

var endpoint = "https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1";

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

然后,我们需要生成一些随机字符串,以便可以在短URL和长URL之间创建链接。

Assume that 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

假设我们有一个随机URL abcd ,我们的简单URL缩短器托管在https://shortner.com上 ,并且已使用该随机URL缩短了URL https://google.com 因此,每当我们转到https://shortner.com/#abcd时,我们都会重定向到https://google.com

So, now well create a function called getrandom():

因此,现在创建一个名为getrandom()的函数:

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

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

不用担心,我会帮助您理解上面的代码。

First, we initiated a function called getrandom. Then we initialized a variable called random_string and gave it a value.

首先,我们启动了一个名为getrandom的函数。 然后,我们初始化了一个名为random_string的变量,并为其提供了一个值。

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).

Math是内置的Javascript对象,它使我们能够对数字执行数学任务。 首先,我们从Math调用了random函数, Math.random()返回一个介于0(含)和1( Math.random()之间的随机数。

You Can Learn More About Math object from here.

您可以从此处了解有关Math对象的更多信息

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

然后,我们使用toString()将返回的数字转换为字符串,并为其指定参数32,以便获得正确的字符串,而不是二进制,十六进制或八进制。

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 +.

然后,我们也使用substring(2,5)对字符串进行切片并保持字符串的大小。 然后再次按照相同的过程获取另一个随机字符串块,最后使用+将字符串的两个块都相加。

And don’t forget to add a return statement returning our random string.

并且不要忘记添加return语句以返回我们的随机字符串。

Remember, this is not the only way to generate random strings. You can also use the method 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;}

Now return to index.html and add JQuery because it will be easier to achieve our goals if we use JQuery. Add it at the end of the body tag but before the main.js script tag.

现在返回index.html并添加JQuery,因为如果使用JQuery,将更容易实现我们的目标。 将其添加到body标签的末尾,但位于main.js脚本标签的main.js

Now again return to main.js.

现在再次返回main.js

Let’s create a function called geturl which will take the value from the input box, verify it, and return the value:

让我们创建一个名为geturl的函数,该函数将从输入框中获取值,进行验证并返回值:

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;     }

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

geturl函数中,我们首先将输入框的值存储在url变量中。 然后,我们检查URL协议是否正确。 如果协议不是以http://https://ftp://开头,我们在URL的开头添加http:// ,然后返回URL。

Actually this isn’t a safe method. You should be using a regex to validate your URLs! But I want to keep this article easy to understand.
实际上,这不是一个安全的方法。 您应该使用正则表达式来验证您的URL! 但我想使本文易于理解。

Now we will need another function to change the hash in the location bar, so let’s create it:

现在,我们将需要另一个函数来更改位置栏中的哈希,因此让我们创建它:

function genhash(){    if (window.location.hash == “”){        window.location.hash = getrandom();    }}

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.

示例:如果我们的URL是https://example.com/#abcd,window.location.hash的值将是#abcd

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

接下来,我们将处理主要函数shorturl() ,让我们开始吧……

function shorturl(){    var longurl = geturl();    genhash();    send_request(longurl);}

First we store the long URL in the longurl variable. Then we add a random hash to the location bar so that we can use the URL as the short URL. Next we call the send_request() with an argument longurl. In this function we send a JSON request to jsonstore to store the long URL with a link to short URL. So now let’s create the send_request() function.

首先,我们将长网址存储在longurl变量中。 然后,我们将随机哈希添加到位置栏,以便可以将URL用作短URL。 接下来,我们使用参数longurl调用send_request() 。 在此函数中,我们向JSONstore发送一个JSON请求,以存储长URL以及指向短URL的链接。 现在让我们创建send_request()函数。

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’    })}

Here we use JQuery to send the JSON request to endpoint+”/” + our random string hash from the location bar. As an example:

在这里,我们使用JQuery将JSON请求发送到endpoint +” /” +我们的位置栏中的随机字符串哈希。 举个例子:

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

So whenever we send a get request to the above-mentioned URL, we’ll get the long URL as data.

因此,每当我们向上述URL发送get请求时,我们都会将长URL作为data

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

重要提示 :在shorturl() send_request()函数之前添加send_request()函数,否则它将不起作用。

To know more about JQuery’s Ajax function, go HERE. To know more about JSON, go HERE.

要了解有关JQuery的Ajax函数的更多信息,请转到此处 要了解有关JSON的更多信息,请转到此处

Now we will use the code to GET the long URL linked to the short URL entered in the address bar:

现在,我们将使用代码来获取链接到在地址栏中输入的短URL的长URL:

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

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

然后,只要我们在地址栏中输入短URL(例如https://shorturl.com/#abcd ),就会执行上述代码。

First, we store the hash value from the URL in the hashh variable.

首先,我们将URL中的哈希值存储在hashh变量中。

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

示例:如果我们的短网址为https://shorted.com/#abcd ,则哈希值将为#abcd。

Then we check if the hash location is empty or not. If it’s not empty we send a get request to the address, endpoint + hashh.

然后,我们检查哈希位置是否为空。 如果不为空,则将get请求发送到地址endpoint + hashh

Example :https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

示例: https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd : https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

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

和往常一样,如果一切正常,我们将从JSON数组数据的数据中获取长URL,然后从该data["result"]提取data["result"]

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

data的值将类似于{"result":longurl,"ok":true} ,其中长URL是您缩短的URL。

Our URL shortener is almost complete! Copy-paste a long URL in the input box then click the Shorten The URL button! Copy the link from the address bar — it’s your short URL!

我们的URL缩短器已接近完成! 在输入框中复制并粘贴一个长URL,然后单击“ 缩短URL”按钮! 复制地址栏中的链接-这是您的短网址!

一些有用的技巧 (Some Useful Tricks)

  • We can add a function to automatically copy the short URL when a user clicks the Shorten The URL button using libraries like SimpleCopy, or ClipboardJS — they’ll copy the short URL which is currently in the location bar.

    我们可以添加一个功能,当用户使用SimpleCopyClipboardJS之类的库单击“ 缩短URL”按钮时,会自动复制该简短URL —他们将复制当前在位置栏中的简短URL。

  • If using SimpleCopy, we can add simplecopy(window.location.href); at the end of the shorturl() function to copy the short URL whenever it shortens a URL.

    如果使用SimpleCopy,我们可以添加simplecopy(window.location.href);shorturl()函数的末尾,以在缩短URL时复制该简短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.

    这个简单的URL缩短器依赖于诸如jsonstore之类的第三方库,因此用它缩短一些机密的长URL不是一个好主意。

  • 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.

    您可以在Github / Gitlab页面上托管整个项目,并设置一个简单的CNAME。 就是这样-您的全新个人URL缩短器已准备就绪! 您可以使用任何静态站点托管服务来托管您的URL缩短器。
  • You can find the full source code of the project on GITHUB

    您可以在GITHUB上找到该项目的完整源代码

That’s it for today! This is my first technical guide, so I apologize for any mistakes.

今天就这样! 这是我的第一本技术指南,对于任何错误我深表歉意。

If you find any problems or mistakes, let me know in the comments below ?.

如果您发现任何问题或错误,请在下面的评论中告诉我?。

Or ping ee on Facebook or Twitter!

或在FacebookTwitter上 ping ee

Peace!

和平!

翻译自: https://www.freecodecamp.org/news/building-a-simple-url-shortener-with-just-html-and-javascript-6ea1ecda308c/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值