Javascript window.location.href - Refreshes page instead of redirecting

33,549

Solution 1

From the Mozilla Developer Network documentation, href is the entire URL of the page. The only relative property in that list is path, which is relative to the host or the domain of the page.

You may also want to look at using the reload or replace method. See How to redirect to another webpage in JavaScript/jQuery?

Solution 2

Somewhat of an edge case, but this problem can also occur if you add event listeners to container divs with anchor tags in them and you want to make each container div, rather than just the anchor tag, clickable and then redirect to the link contained within the anchor tag's href attribute. In this case, you want to include event.preventDefault() to prevent this behavior.

Vanilla JS

document.getElementById("myAnchorDiv").addEventListener("click", function(event){
   event.preventDefault();

    //get url 
    URL = ...

   //Below Line should now work
   window.location.href = URL;
});

jQuery

$("#myAnchorDiv").on("click", function( event ) {
    event.preventDefault();

    //get url 
    URL = ...

    //Below Line should now work
    window.location.href = URL;

 });

If you want, you can of course combine the last two lines of code into just one line of code, i.e. something like window.location.href = [your URL];

Solution 3

Try: location.href = location.origin + "/Process.aspx";

Share:
33,549
gbam
Author by

gbam

Updated on April 08, 2021

Comments

  • gbam
    gbam about 3 years

    I'm using window.location.href to redirect my browser and I am not sure why one works and one doesn't. When I use a relative link, it refreshes the current page. When I use the full url it redirects. The page I'm on and the Process.aspx page are on the same directory level. So I should just be able to have a relative link? When I do that though it just reloads the current page I'm on. What basic idea am I missing about window.location.href?

        $(document).ready(function() {
    
        $( "button" )
            .button();
        $("#cancel")
            .click(function( event ) {
                alert("click");
    
                //Below Line Doesn't work
                window.location.href = "/Process.aspx";
    
                //Below Line Does work
                window.location.href = "http://localhost:65215/Process.aspx";
        });
    });