JavaScript 中的 Location 协议属性
本文将教我们如何使用 Javascript location 协议属性来实现 Web 应用程序的协议。
JavaScript 中的只读 location.protocol 属性返回当前网页 URL 中指定的协议。它提供了有关 URL 协议的详细信息,包括“http:”、“https:”、“file:”等。
许多 Web 应用程序使用的常见协议值包括:
http − 表示超文本传输协议 (HTTP)。
https − 表示超文本传输协议安全 (HTTPS)。
file − 表示文件传输协议 (FTP)。
ftp − 表示文件传输协议 (FTP)。
data − 表示数据 URI。
mailto − 表示电子邮件链接。
要访问当前 URL 中使用的协议,我们可以使用 location.protocol 属性。
让我们看一些示例来更好地理解这个概念:
示例 1
在此示例中,我们将创建一个按钮元素并向其添加一个点击事件监听器。当单击按钮时,我们将调用 checkProtocol() 函数并检查 location.protocol 值,然后根据协议是否为“https:”显示相应的警报消息。
文件名:index.html
<html>
<head>
<title>Location protocol Property in JavaScript.</title>
</head>
<body>
<h3>Location protocol Property in JavaScript.</h3>
<button onclick="checkProtocol()">Check Protocol</button>
<script>
function checkProtocol() {
if (location.protocol === 'https:') {
alert('This webpage is served over a secure connection.');
} else {
alert('This webpage is served over an insecure connection.');
}
}
</script>
</body>
</html>
输出
输出将如下所示:

示例 2
在此示例中,我们将创建一个按钮元素并向其添加一个点击事件监听器。当单击按钮时,我们将调用 findSecuredUrl() 函数并检查当前协议是否不是“https:”。如果不是,则该函数会将当前 URL 的安全版本打印到控制台。
文件名:index.html
<html>
<head>
<title>Protocol Redirect Example</title>
<script>
function findSecuredUrl() {
if (location.protocol !== 'https:') {
const securedUrl = 'https://' + location.host + location.pathname;
console.log('securedUrl', securedUrl);
}
}
</script>
</head>
<body>
<h3>Protocol Redirect Example</h3>
<button onclick="findSecuredUrl()">Redirect to Secure Protocol</button>
</body>
</html>
输出
输出将如下所示:

结论
我们可以使用 JavaScript 的 location.protocol 属性检索当前网页 URL 中列出的协议。它允许我们识别 URL 的协议部分,例如“http:”、“https:”等。在使用条件逻辑或根据所用协议做出决策时,此信息可能会有所帮助。我们学习了 JavaScript 中 location 协议属性的概念,并查看了一些解释该属性的示例。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP