最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to get the current URL with JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I would like to get my current URL address, save it to a variable and then pass it to an HTML element:

const url = document.URL;
document.getElementById("url").innerHTML = url;

I have tried using document.URL, window.location and window.location.href but none of them works for me. It displays nothing.

My HTML is:

<html>

<head>
  <script>
    const url = location.href;
    document.getElementById("url").innerHTML = url;

    function first() {
      console.log("It works!");
    }

    function submit() {
      let result;
      result = confirm("Would you like to confirm your change?");
      if (result == true)
        window.location = "okay.html";
      else if (result == false)
        console.log("You have clicked the \"cancel\" button.");
    }
  </script>
</head>

<body>
  <input type="button" onclick="first()" value="Try Me" />

  <p onmouseover="submit()">Hover over this text.</p>

  <p id="url">error</p>
</body>

</html>

I would like to get my current URL address, save it to a variable and then pass it to an HTML element:

const url = document.URL;
document.getElementById("url").innerHTML = url;

I have tried using document.URL, window.location and window.location.href but none of them works for me. It displays nothing.

My HTML is:

<html>

<head>
  <script>
    const url = location.href;
    document.getElementById("url").innerHTML = url;

    function first() {
      console.log("It works!");
    }

    function submit() {
      let result;
      result = confirm("Would you like to confirm your change?");
      if (result == true)
        window.location = "okay.html";
      else if (result == false)
        console.log("You have clicked the \"cancel\" button.");
    }
  </script>
</head>

<body>
  <input type="button" onclick="first()" value="Try Me" />

  <p onmouseover="submit()">Hover over this text.</p>

  <p id="url">error</p>
</body>

</html>

Share Improve this question edited Aug 6, 2024 at 11:59 Samuel RIGAUD 1,7021 gold badge17 silver badges27 bronze badges asked Sep 12, 2012 at 15:12 GrobiGrobi 1491 gold badge2 silver badges10 bronze badges 5
  • 1 location.href is fine. Did you try alerting it? – MaxArt Commented Sep 12, 2012 at 15:14
  • Show us the error message from the console. Does it say that document.getElementById("url") was null? – Bergi Commented Sep 12, 2012 at 15:19
  • your JS code comes after the <p> or before? If before - the element doesn't exist when you executing the JS – Zoltan Toth Commented Sep 12, 2012 at 15:19
  • 2 This is probably a case of running the script before the element exists. Make sure your script is after you element with the id "url": jsfiddle.net/hu4Gq/1 – Paul Commented Sep 12, 2012 at 15:19
  • Thanks! That solved it. The problem was that my script was before my element. – Grobi Commented Sep 12, 2012 at 15:25
Add a comment  | 

3 Answers 3

Reset to default 7

Now that you have disclosed your entire code, we can see that you are running document.getElementById("url") too soon before the DOM is loaded. Move your script to the end of the body tag (see fixed code at the end of this answer).

Scripts that reference DOM elements cannot be run until those DOM elements are successfully loaded. There are three ways to ensure that.

  1. The simplest is to just place the script right before the </body> tag. Since things in the <body> tag are loaded sequentially, this ensures that all of your page has been loaded before the script runs and thus the script can reference it.

  2. You can code your script to wait for everything in the page to finish loading (including images) by running your code only when the window.onload event fires. This waits longer than necessary because it also waits for all images to finish loading, but it is safe and easy.

  3. You can code your script to wait until just the DOM is loaded. This is a little tricky to do cross browser since older browsers require different mechanisms. In newer browsers, this time is signified with a DOMContentLoaded event on the document.

window.location.href contains the current page URL. This always works and is the correct way to obtain the URL of the current page.

Working demo: http://jsfiddle.net/jfriend00/yGrxU/

If this doesn't work in your page, then you have something else wrong in your code. It could be because you are running your code too early before the DOM is loaded and thus document.getElementById() isn't working. You can fix that by moving your javascript code to the end of the body tag.

Another possibility is that you have a script error in your page that is stopping execution of your javscript. You should check the browser error console or the debug console to see if there are any script errors being reported.


Now that you've posted your entire code, we can see that you need to move the script to right before the </body> tag like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>

  <style type="text/css">

    input:hover
    {
        background: black;
        color: white;   
        border: 0;      
    }

  </style>


</head>

<body>

  <input type="button" onclick="first()" value="Try Me" />

  <p onmouseover="submit()">Hover over this text.</p>

  <p id="url">error</p>

  <script>   

  var url = location.href;
  document.getElementById("url").innerHTML = url;

  function first()
  {
    var string = "It works!";
    write(string);
  }

  function write(szoveg)
  {
      alert(szoveg);
  }

  function submit()
  {
      var result;
      result = confirm("Would you like to confirm your change?");
      if(result==true) 
          window.location="okay.html";
      else if(result==false)
          alert("You have clicked the \"cancel\" button.");

  }  

  </script>
</body>

</html>

Try this , you can botain the url of your page and put it into a variable

window.location.href

Your problem is that these two lines:

var url = location.href;
document.getElementById("url").innerHTML = url;

Execute before your <p> tag exists. Remove them from your script and add a new script after your p tag:

<p id="url"></p>
<script>
    var url = location.href;
    document.getElementById("url").innerHTML = url;
</script>

See this JSFiddle

It might be even nicer to use a script that replaces itself with a text node containing the url. Then you don't need to give the p an id if you don't use that id anywhere else:

<p>
    <script>
      (function(){
        var scripts = document.getElementsByTagName('script');
        var this_script = scripts[scripts.length - 1];
        this_script.parentNode.replaceChild(
          document.createTextNode(location.href),
          this_script
        );
      })();
    </script>
</p>

See this JSFiddle

发布评论

评论列表(0)

  1. 暂无评论