如何在 JavaScript 中顯示載入文件的伺服器域名?
在本文中,我們將學習如何在 JavaScript 中顯示載入文件的伺服器域名。
要顯示伺服器的域名,我們使用 document 介面的 domain 屬性,該屬性返回當前文件的域名部分。如果文件是在記憶體中建立的,則 domain 屬性將返回 NULL。嘗試設定 document 介面的 domain 屬性會導致 **SecurityError** 錯誤。
為了更好地理解,讓我們透過 JavaScript 中的合適示例瞭解 domain 屬性的語法和用法。
使用 domain 屬性
我們可以使用 JavaScript 的 domain 屬性獲取載入伺服器的域名。
語法
以下是 JavaScript 的 domain 屬性的語法:
document.domain
domain 屬性返回伺服器的域名。如果文件是在記憶體中建立的,則 domain 屬性返回 **null**。
示例 1
在以下示例中,我們使用 domain 屬性獲取載入伺服器的域名。
<html>
<body>
<p id="domain"></p>
<script>
document.getElementById("domain").innerHTML = 'The domain name is :'+" "+document.domain;
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
示例 2
以下是一個示例程式,用於使用 **document.domain** 顯示路徑 https://cloud.google.com/run/docs/mapping-custom-domains 的域名。
<!DOCTYPE html>
<html>
<head>
<title>To display the domain of the server that loaded a document in JavaScript</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="text-align : center">
<h3>To display the domain of the server that loaded a document in JavaScript</h3>
<p id='domain'></p>
<script>
document.getElementById('domain').innerHTML = 'The domain name is : '+document.domain;
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
使用 location.hostname 屬性
我們可以使用 JavaScript 的 location hostname 屬性獲取載入伺服器的域名。
語法
以下是 JavaScript 的 location.hostname 屬性的語法:
document.location.hostname;
返回字串形式的域名。
示例
以下是一個示例程式,用於使用 **document.location.hostname** 顯示路徑 https://cloud.google.com/run/docs/mapping-custom-domains 的域名。
<!DOCTYPE html>
<html>
<head>
<title>To display the domain of the server that loaded a document in JavaScript</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="text-align : center">
<h3>To display the domain of the server that loaded a document in JavaScript</h3>
<p id='domain'></p>
<script>
document.getElementById('domain').innerHTML = 'The domain name is : '+document.location.hostname;
</script>
</body>
</html>
執行上述程式碼後,將生成以下輸出。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP