I have this code:
$(window).ready(function() {
var url = window.location.href;
if (url.includes("#/projet/")) {
projectId = url.substring(url.indexOf("#")+1).split("/").slice(2, 3).toString();
window.location.href = "projects/" + projectId;
};
})
I'm redirected but the window.location is not replaced, just concatenated.
For instance, if my URL is localhost:3000/users/212323/dashboard, after the javascript redirection, I get localhost:3000/users/212323/projects/123456 instead of localhost:3000/projects/123456
I don't understand why the href is concatenated and not replaced, do you have an idea?
window.location.href = 'someurl' works the same way as clicking that someurl in a <a> tag.
When using a relative path (i.e. without / in the beginning), your browser will concatenate the URL to the existing URL.
Simple fix in your case is to prepend the /:
window.location.href = "/projects/" + projectId;
Note though, that this will cause the site possibly not work anymore if it is moved to another location. That is why many web frameworks use full URLs and some kind of base-url to get the linking correctly.
You need to add another / to the beginning of the url, otherwise the browser interprets the url as a relative url to the curent url.
window.location.href = "/projects/" + projectId;
The extra / at the start tells the browser to start from the root url.
Given a url www.site.com/test, how can I route to www.site.com/#testinner with javascript, without hardcoding base url? By route - I mean including a refresh / page load.
This gives me settings#lol:
var desiredBase = window.location.protocol + "//" + window.location.host + "/";
var path = '#lol';
window.location.href = desiredBase + path;
location.reload();
You can just search for /test at the end of the and replace it with /#testinner. Here's an example:
window.location.href = window.location.href.replace(/\/test$/, "/#testinner");
Here's a snippet showing the basic idea. You can see that it automatically navigates to the #testinner bookmark without having to refresh the page. Of course, the snippet's URL doesn't end in /test so I had to modify what it's replacing, and /#testinner doesn't exist inside the snippet so I had to modify that a bit as well. But the concept is the same. I've also included the current URL in the markup, since you can't see that very easily within the snippet.
document.getElementById("currUrl").innerText = location.href;
location.href = location.href.replace(/\/js$/, "/js#testinner");
document.getElementById("currUrl").innerText = location.href;
.vert-spacer {
height: 800px;
}
<div class="vert-spacer"></div>
<div id="testinner">Test Bookmark</div>
Current URL: <span id="currUrl"></span>
I have a situation where I need to get the current page url and redirect to a new page by adding to the current page url. For example:
http://www.mywebsite.com/page1/page2
needs to redirect to:
http://www.mywebsite.com/page1/page2/page3
I need it to be relative because "/page1/page2/" will always be different, but "page3" will always be the same.
I've tried: location.href = "./page3"; but that does not work. The result is:
http://www.mywebsite.com/page1/page3
Any thoughts?
Maybe this?:
location.href = location.pathname + "/page3";
Get and Set URL using either window.location.href or document.URL;
window.location.href = window.location.href + "/page3";
Should do what you're looking for.
I have Scenario like: Below,
Following a "Menu List" having href value set to corresponding ".htm" Pages inside "Menu.html"
Click Me to got to pageOne.htm
Click Me to got to pageTwo.htm
Click Me to got to pageThree.htm
Click Me to got to pageFour.htm
Each Pages pageOne.htm, pageTwo.htm & pageThree.htm etc.. are having footer part, In footer it must be like it has to contain 3 Links with href values.
I require a solution:
If my Current page is pageOne.htm the Footer should show me shortcuts links to pageTwo.htm, pageThree.htm and pageFour.htm and wise verse depending on my current page.
So I require code to Get .htm from URL pathname.
Can we find() method of Jquery after getting the URL PATH like find(".htm") from URL.
Require just a snippet of Code to get the .htm page name alone.
Including an sample case below:
What if the Url is Like >>
"http://<10.10.21.26:9080>/myTestAoo/pageThree.htm#detailView"
I wish to get the value "pageThree.htm" alone from above url, if its the current page.
Thanks in advance
var lastPartOfUrl = document.URL.split('/').pop();
Or with regular expression:
var regexp = /([^\/]+)(.htm)/;
var match = regexp.exec(document.URL);
console.log(match[0]); // pageThree.htm
console.log(match[1]); // pageThree
console.log(match[2]); // .htm
The following will give you the current URL, which you can tidy up using replace():
window.location.href
you may try this code:
var a = window.location.href;
var fileName = a.substring(a.lastIndexOf('/')+1);
alert(fileName);
use window.location.pathname; will returns the full path
try following function
function getFileName(){
var url = window.location.pathname;
var path=url.split("/");
var filname=path[path.length-1];
return filname;
}
Is there a way to update the URL programatically without reloading the page?
EDIT: I added something in the title in post .I just want to make it clear that I don't want to reload the page
Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.
However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Yes - document.location = "http://my.new.url.com"
You can also retrieve it the same way eg.
var myURL = document.location;
document.location = myURL + "?a=parameter";
The location object has a number of useful properties too:
hash Returns the anchor portion of a URL
host Returns the hostname and port of a URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
port Returns the port number the server uses for a URL
protocol Returns the protocol of a URL
search Returns the query portion of a URL
EDIT:
Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)
EDIT2: To make it clear, not just in a comment:
You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.
You can use :
window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
Use
window.history.replaceState({}, document.title, updatedUri);
To update Url without reloading the page
var url = window.location.href;
var urlParts = url.split('?');
if (urlParts.length > 0) {
var baseUrl = urlParts[0];
var queryString = urlParts[1];
//update queryString in here...I have added a new string at the end in this example
var updatedQueryString = queryString + 'this_is_the_new_url'
var updatedUri = baseUrl + '?' + updatedQueryString;
window.history.replaceState({}, document.title, updatedUri);
}
To remove Query string without reloading the page
var url = window.location.href;
if (url.indexOf("?") > 0) {
var updatedUri = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, updatedUri);
}
Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.
var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);
Yes
document.location is the normal way.
However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.
Check out this thread on SO for more info:
What's the difference between window.location and document.location in JavaScript?
Prefix URL changes with a hashtag to avoid a redirect.
This redirects
location.href += '&test='true';
This doesn't redirect
location.href += '#&test='true';
Plain javascript: document.location = 'http://www.google.com';
This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.
You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.
If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page
Yes - document.location.hash for queries