JavaScript 現在のページのURLとドメインを取得するサンプル

環境
Google Chrome 123.0.6312.58(Official Build) (64 ビット)
Windows 11 Pro 64bit

構文
document.URL
document.URLを使うと、現在のURLを取得します。

document.URL使い方
console.log(document.URL);

document.domainを使うと、現在のドメインのみ取得します
console.log(document.domain);

使用例

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

<head>
  <meta charset="utf-8">
  <title>サンプル</title>
</head>
<script>

  function test() {   
    // URL
    document.getElementsByClassName('badge-primary')[0].textContent = document.URL;
    // ドメイン
    document.getElementsByClassName('badge-primary')[1].textContent = document.domain;

  }

</script>

<body>
  <div class="main">
    
    <h5><span class="badge badge-primary">URL</span></h5>
    <h5><span class="badge badge-primary">ドメイン(IP)</span></h5>

    <button type="button" class="btn btn-raised btn-warning" onclick="test()">取得</button>

  </div>
</body>

</html>

 

JavaScript

Posted by arkgame