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 協議屬性的概念,並查看了一些解釋該屬性的示例。

更新於: 2023-08-16

160 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.