javascript アクセス中のホスト名を取得する

javascript アクセス中のホスト名を取得する

javascriptで、アクセス中のホスト名を取得するサンプルコードを記述してます。「location.hostname」で取得できます。

環境

  • OS windows11 home
  • ブラウザ chrome 108.0.5359.125

アクセス中のホスト名を取得

アクセス中のホスト名を取得するには、「location.hostname」を使用します。

console.log( location.hostname );
// 結果 ホスト名

サンプルコード

以下は、実行ボタンをクリックするとホスト名を取得して表示するだけのサンプルコードとなります。

※cssには「Material Design for Bootstrap」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- Font Awesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.1.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-25" style="margin-top:150px">

    <div id="result" class="alert alert-danger"></div>

    <button id="btn" class="btn btn-danger btn-rounded ">実行</button>

  </div>

  <script>

    btn.addEventListener('click', () => {      

      // 表示
      result.innerHTML = location.hostname;

    });

  </script>

</body>

</html>

表示されていることが確認できます。