如何在 JavaScript 中獲取當前頁面網際網路主機埠的埠號?


在本教程中,我們將學習如何在 JavaScript 中獲取當前頁面的網際網路主機埠號。

埠號是協議的 16 位唯一 ID。埠號範圍從 0 到 65535。埠號用於伺服器查詢程序。共有 65535 個埠號,每個埠號都與其標識相關聯。

因此,讓我們看看如何在 JavaScript 中獲取當前頁面的埠號。

以下是我們可以獲取網際網路主機埠號的方法:

  • 使用 location.port 屬性
  • 使用 URL 介面

使用 location.port 屬性

Location 是訪問物件 URL 的介面。Windows 和 Document 物件都可以訪問此介面。location 介面包含許多屬性,其中 port 是其中之一。location.port 返回 URL 的埠號。

語法

//get a port number
var port_number= location.port;

在以上語法中,使用者可以看到,透過使用 location.port,您可以獲取當前頁面的埠號。我們必須根據語法將值儲存在變數中。

示例 1

在下面給出的示例中,我們使用了 location.port 方法在 JavaScript 中獲取埠號。

<html> <body> <h3> Use <i> location.port </i> to get a port number using JavaScript. </h3> <button id = "btn">get port</button> <p id = "para"> </p> <p><b>Note: </b>If the port number is default (80 for http and 443 for https), most browsers will display nothing.</p> <script> var port_number= location.port; document.getElementById("btn").addEventListener("click",getport); function getport(){ document.getElementById("para").innerHTML="Port Number of the page: "+port_number; } </script> </body> </html>

在上面的示例中,使用者可以看到我們使用了 location.port 方法來獲取當前頁面網際網路主機的埠號。我們添加了一個按鈕,單擊該按鈕將執行一個函式。並在函式內部添加了我們的方法來獲取埠。

使用 URL 介面

URL 介面用於編碼 URL。該介面為我們提供了許多屬性來訪問主機、域名或埠等。它包含一個 port 屬性,其中包含 URL 的埠。

觀眾可以按照以下語法使用 URL 介面在 JavaScript 中獲取當前頁面的埠號。

語法

var URL= new URL(window.location.href);
var port_number = URL.port; 

在此語法中,首先,我們從 location 物件訪問了當前 URL,然後在 URL 上使用了 port 方法。

示例

在下面給出的示例中,我們使用了 URL 介面在 JavaScript 中獲取當前頁面網際網路主機的埠號。

<html> <body> <h3> Use <i> URL interface </i> to get a port number using JavaScript. </h3> <button id = "btn">get port</button> <p id = "para"> </p> <p><b>Note: </b>If the port number is default (80 for http and 443 for https), most browsers will display nothing.</p> <script> var URL= new URL(window.location.href); var port_number = URL.port; document.getElementById("btn").addEventListener("click",getport); function getport(){ document.getElementById("para").innerHTML="Port Number of the page: "+port_number; } </script> </body> </html>

在上面的示例中,使用者可以看到我們使用了 URL 介面方法來獲取當前頁面網際網路主機的埠號。此示例與上一個示例相同;我們只是在這裡使用了 URL 介面。

在本教程中,我們看到了兩種在 JavaScript 中獲取當前頁面網際網路主機埠號的方法。這兩種方法都簡單易於實現,因為它們不包含任何邏輯。

更新於: 2022-10-12

470 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.