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.ly , goo.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.

    我们可以添加一个功能,当用户使用SimpleCopy或ClipboardJS之类的库单击“ 缩短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!

或在Facebook或Twitter上 ping ee !

Peace!

和平!

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

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

  1. aws lambda使用_如何使用AWS Lambda和S3构建无服务器URL缩短器

    aws lambda使用 by Daniel Ireson 丹尼尔·埃里森(Daniel Ireson) 如何使用AWS Lambda和S3构建无服务器URL缩短器 (How to build a S ...

  2. 给一个div innerhtml 后 没有内容显示的问题_实战:仅用18行JavaScript构建一个倒数计时器...

    有时候,你会需要构建一个JavaScript倒计时时钟.你可能会有一个活动.一个销售.一个促销或一个游戏.你可以用原生的JavaScript构建一个时钟,而不是去找一个插件.尽管有很多很棒的时钟插件, ...

  3. 如何使用CSS和JavaScript构建简单的甘特图

    到目前为止,在我们CSS图表系列教程中,我们已经学习了如何创建不同类型的图表,包括条形图,温度计图和饼图. 今天,我们将通过在甘特图中构建和呈现数据来继续这一旅程. 与其他图表教程不同,我们将大量使用 ...

  4. vanilla_如何使用Vanilla JavaScript构建简单的全屏幻灯片

    vanilla 在本教程中,您将学习如何使用纯JavaScript创建响应式全屏幻灯片. 要构建它,我们将经历几个不同的前端技巧. 另外,当我们将鼠标悬停在幻灯片上时,我们将更进一步,自定义光标的外观 ...

  5. 使用Express和MongoDB构建简单的CRUD应用程序

    by Zell Liew 由Zell Liew 使用Express和MongoDB构建简单的CRUD应用程序 (Building a Simple CRUD Application with Expr ...

  6. electron 桌面程序_如何使用Electron使用JavaScript构建您的第一个桌面应用程序

    electron 桌面程序 by Carol-Theodor Pelu 通过Carol-Theodor Pelu 如何使用Electron使用JavaScript构建您的第一个桌面应用程序 (How ...

  7. 如何使用 JavaScript 构建计算器应用程序

    这个史诗般的教程通过描述如何使用该语言开发一个简单的计算器应用程序,为 JavaScript 新手提供了一个可靠的练习. 面向初学者的 javascript 项目(8 部分系列) 1 构建你的第一个 ...

  8. HTML5游戏开发进阶指南(亚马逊5星畅销书,教你用HTML5和JavaScript构建游戏!)

    HTML5游戏开发进阶指南(亚马逊5星畅销书,教你用HTML5和JavaScript构建游戏!) [印]香卡(Shankar,A.R.) 著 谢光磊 译 ISBN 978-7-121-21226-0 ...

  9. css菜单缓慢滑动_如何使用HTML,CSS和JavaScript构建滑动菜单栏

    css菜单缓慢滑动 by Supriya Shashivasan 由Supriya Shashivasan 如何使用HTML,CSS和JavaScript构建滑动菜单栏 (How to build a ...

最新文章

  1. 如何实现流畅观影体验?视频类应用内存和CPU大调查
  2. 华为存储iscsi配置_iscsi 华为存储配置 上课内容
  3. mat opencv 修改roi_OpenCV中如何提取不规则ROI区域
  4. 数据结构——堆的C语言实现
  5. javascript图片库威力增强版
  6. apache简单安全配置
  7. Xshell免密登录
  8. N76E003驱动WS2811实现渐变色、跑马灯
  9. 单片机 队列 C语言 OLED 示波器 心率波形 显示 MSP430F5529 pulsesensor ADS1292R
  10. C#语言自定义平方根函数
  11. 【HTML+CSS】自定义字体
  12. MindManager2021下载及安装教程
  13. VOIP技术连载之二--VOIP呼叫流程
  14. 电脑开始菜单没有了关机选项,怎么办
  15. matlab绘制银河系,科学家们是如何绘制宇宙星系图的?
  16. daphile的dsd设置_小块头有大能量 篇二:JaguarBoard之Daphile HiFi 畅享
  17. Uniapp 制作海报功能
  18. 【教3妹学算法-每日3题(3)】 判断矩阵经轮转后是否一致
  19. java编程基础答案_Java编程基础答案试题题目及答案,期末考试题库,章节测验答案...
  20. 影响力最大化,传播模型

热门文章

  1. css炫酷标题,纯css3鼠标滑过图片炫酷标题显示特效
  2. Swift 圆环进度条
  3. HDFS的shell和API操作
  4. h5 移动端 关于监测切换程序到后台或息屏事件和visibilitychange的使用
  5. 彻底理解OkHttp - OkHttp 源码解析及OkHttp的设计思想
  6. 【对讲机的那点事】关于对讲机锂电池你了解多少?
  7. Solaris下ftp配置(初稿-待补充)
  8. [ExtJS5学习笔记]第五节 使用fontawesome给你的extjs5应用添加字体图标
  9. C#实现php的hash_hmac函数
  10. Windows系统安装Oracle 11g客户端