Javascript/jQuery get root url of website - javascript

I have website:
"http://www.example.com/folder1/mywebsite/subfolder/page.html"
Root of the site is: "http://www.example.com/folder1/mywebsite"
I would like to get root url of "mywebsite" dynamicly.
If I will publish this site to another place, then I will no need to change script.
For example to: "http://www.example.com/otherFolder/test/myChangedWebsite/subfolder/page.html"
I will get:
"http://www.example.com/otherFolder/test/myChangedWebsite"
I tried in "page.html" javascript:
var url = window.location.protocol + "//" + window.location.host + '/otherPage.html
but this gives me only "http://www.example.com/otherPage.html".
Also I know about location.origin but this is not supported for all browser as I found that on link: http://www.w3schools.com/jsref/prop_loc_origin.asp
If it can be done with jQuery, it will be good as well.

Here's a function doing the same as Hawk's post above, only much, much shorter:
function getBaseUrl() {
var re = new RegExp(/^.*\//);
return re.exec(window.location.href);
}
Details here: Javascript: Get base URL or root URL

Use the following javascript to get the root of your url:
window.location.origin
For more details:
[https://www.codegrepper.com/code-examples/javascript/javascript+get+root+url][1]

slightly shorter:
function getBaseUrl() {
return window.location.href.match(/^.*\//);
}

if your location is fixed after mywebsite/subfolder/page.html"
then use this
location.href.split("mywebsite")[0]

Related

window location get the URL [duplicate]

All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I please.
Use:
window.location.href
As noted in the comments, the line below works, but it is bugged for Firefox.
document.URL
See URL of type DOMString, readonly.
URL Info Access
JavaScript provides you with many methods to retrieve and change the current URL, which is displayed in the browser's address bar. All these methods use the Location object, which is a property of the Window object. You can read the current Location object by reading window.location:
var currentLocation = window.location;
Basic URL Structure
<protocol>//<hostname>:<port>/<pathname><search><hash>
protocol: Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname: Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port: A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname: The path gives info about the specific resource within the host that the Web client wants to access. For example, /index.html.
search: A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash: The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components and what they can set or return:
href - the entire URL
protocol - the protocol of the URL
host - the hostname and port of the URL
hostname - the hostname of the URL
port - the port number the server uses for the URL
pathname - the path name of the URL
search - the query portion of the URL
hash - the anchor portion of the URL
origin - the window.location.protocol + '//' + window.location.host
I hope you got your answer..
Use window.location for read and write access to the location object associated with the current frame. If you just want to get the address as a read-only string, you may use document.URL, which should contain the same value as window.location.href.
Gets the current page URL:
window.location.href
OK, getting the full URL of the current page is easy using pure JavaScript. For example, try this code on this page:
window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"
The window.location.href property returns the URL of the current page.
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<h3>The window.location.href</h3>
<p id="root"></p>
</body>
</html>
Just not bad to mention these as well:
if you need a relative path, simply use window.location.pathname;
if you'd like to get the host name, you can use window.location.hostname;
and if you need to get the protocol separately, use window.location.protocol
also, if your page has hash tag, you can get it like: window.location.hash.
So window.location.href handles all in once... basically:
window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
//true
Also using window is not needed if already in window scope...
So, in that case, you can use:
location.protocol
location.hostname
location.pathname
location.hash
location.href
To get the path, you can use:
console.log('document.location', document.location.href);
console.log('location.pathname', window.location.pathname); // Returns path only
console.log('location.href', window.location.href); // Returns full URL
Open Developer Tools, type in the following in the console and press Enter.
window.location
Ex: Below is the screenshot of the result on the current page.
Grab what you need from here. :)
Use: window.location.href.
As noted above, document.URL doesn't update when updating window.location. See MDN.
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can get the current URL location with a hash tag by using:
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
jQuery:
$(location).attr('href');
For complete URL with query strings:
document.location.toString()
For host URL:
window.location
// http://127.0.0.1:8000/projects/page/2?name=jake&age=34
let url = new URL(window.location.href);
/*
hash: ""
host: "127.0.0.1:8000"
hostname: "127.0.0.1"
href: "http://127.0.0.1:8000/projects/page/2?username=jake&age=34"
origin: "http://127.0.0.1:8000"
password: ""
pathname: "/projects/page/2"
port: "8000"
protocol: "http:"
search: "?name=jake&age=34"
username: ""
*/
url.searchParams.get('name')
// jake
url.searchParams.get('age')
// 34
url.searchParams.get('gender')
// null
To get the path, you can use:
http://www.example.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
window.location.host www.example.com:8082
window.location.hostname www.example.com
window.location.port 8082
window.location.protocol http:
window.location.pathname index.php
window.location.href http://www.example.com:8082/index.php#tab2
window.location.hash #tab2
window.location.search ?foo=789
window.location.origin https://example.com
var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
currentPageUrlIs = this.href.toString().toLowerCase();
}else{
currentPageUrlIs = document.location.toString().toLowerCase();
}
The above code can also help someone
Adding result for quick reference
window.location;
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ, …}
document.location
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ
, …}
window.location.pathname
"/questions/1034621/get-the-current-url-with-javascript"
window.location.href
"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
location.hostname
"stackoverflow.com"
For those who want an actual URL object, potentially for a utility which takes URLs as an argument:
const url = new URL(window.location.href)
https://developer.mozilla.org/en-US/docs/Web/API/URL
Nikhil Agrawal's answer is great, just adding a little example here you can do in the console to see the different components in action:
If you want the base URL without path or query parameter (for example to do AJAX requests against to work on both development/staging AND production servers), window.location.origin is best as it keeps the protocol as well as optional port (in Django development, you sometimes have a non-standard port which breaks it if you just use hostname etc.)
You have multiple ways to do this.
1:
location.href;
2:
document.URL;
3:
document.documentURI;
Use this:
var url = window.location.href;
console.log(url);
In jstl we can access the current URL path using pageContext.request.contextPath. If you want to do an Ajax call, use the following URL.
url = "${pageContext.request.contextPath}" + "/controller/path"
Example: For the page http://stackoverflow.com/posts/36577223 this will give http://stackoverflow.com/controller/path.
The way to get the current location object is window.location.
Compare this to document.location, which originally only returned the current URL as a string. Probably to avoid confusion, document.location was replaced with document.URL.
And, all modern browsers map document.location to window.location.
In reality, for cross-browser safety, you should use window.location rather than document.location.
location.origin+location.pathname+location.search+location.hash;
and
location.href
does the same.
You can get the full link of the current page through location.href
and to get the link of the current controller, use:
location.href.substring(0, location.href.lastIndexOf('/'));
Short
location+''
let url = location+'';
console.log(url);
Getting the current URL with JavaScript :
window.location.toString();
window.location.href
if you are referring to a specific link that has an id this code can help you.
$(".disapprove").click(function(){
var id = $(this).attr("id");
$.ajax({
url: "<?php echo base_url('index.php/sample/page/"+id+"')?>",
type: "post",
success:function()
{
alert("The Request has been Disapproved");
window.location.replace("http://localhost/sample/page/"+id+"");
}
});
});
I am using ajax here to submit an id and redirect the page using window.location.replace. just add an attribute id="" as stated.
let url = new URL(window.location.href);
console.log(url.href);
Use the above code to get the current URL of the website.
or try this - https://bbbootstrap.com/code/get-current-url-javascript-54628697
Firstly check for page is loaded completely in
browser,window.location.toString();
window.location.href
then call a function which takes url, URL variable and prints on console,
$(window).load(function(){
var url = window.location.href.toString();
var URL = document.URL;
var wayThreeUsingJQuery = $(location).attr('href');
console.log(url);
console.log(URL);
console.log(wayThreeUsingJQuery );
});

javascript window.open without http://

I have a small tool build with Delphi that collects url's from a file or from the clipboard, and than builds a file called test.htm with a content like this :
<!DOCTYPE html>
<html>
<body>
<p>Click the button retrieve the links....</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
window.open('http://www.speedtest.net/', '_blank');
window.open('www.speedtest.net/', '_blank');
and so on...
}
</script>
</body>
</html>
The idea is to click on the button, and then a new tab (or window) is created for every url inside myFunction.
This works, but with one small problem.
In the code example there are 2 url's, one with the http:// prefix and one without it. The first url works as expected and creates a new tab (or window) with the following url:
http://www.speedtest.net
The second 'window.open' does not work as I expected. This 'window.open' will create the following url in the new tab (or window)
file:///c:/myApplicaton/www.speedtest.net
As you have already figured out, the application is an executable in c:\myApplication
So my question(s) is, is there a way to use 'window.open' to create a new tab (or window) without putting the path of the application in front of the url ?
If this is not possible with 'window.open', is there another way to do this ?
Or is the only way to do this to have the application put the http:// in front of every url that does not have it already ?
As you suggested, the only way is to add the http protocol to each URL which is missing it. It's a pretty simple and straightforward solution with other benefits to it.
Consider this piece of code:
function windowOpen(url, name, specs) {
if (!url.match(/^https?:\/\//i)) {
url = 'http://' + url;
}
return window.open(url, name, specs);
}
What I usually do is to also add the functionality of passing specs as an object, which is much more manageable, in my opinion, than a string, even setting specs defaults if needed, and you can also automate the name creation and make the argument optional in case it's redundant to your cause.
Here's an example of how the next stage of this function may look like.
function windowOpen(url, name, specs) {
if (!url.match(/^https?:\/\//i)) {
url = 'http://' + url;
}
// name is optional
if (typeof name === 'object') {
specs = name;
name = null;
}
if (!name) {
name = 'window_' + Math.random();
}
if (typeof specs === 'object') {
for (var specs_keys = Object.keys(specs), i = 0, specs_array = [];
i < specs_keys.length; i++) {
specs_array.push(specs_keys[i] + '=' + specs[specs_keys[i]]);
}
specs = specs_array.join(',');
}
return window.open(url, name, specs);
}
I think the best way would be to add "//" + url
In this case - it isn't important, what protocol (http or https) you expect to receive as a result.
url = url.match(/^https?:/) ? url : '//' + url;
window.open(url, '_blank');
The only way to do this is to have the application put the http:// in front of every url that does not have it already.
For the behavior you're describing, you have to include your protocol with window.open. You could use a tertiary operator to simply include the protocol if it doesn't already exist:
url = url.match(/^http[s]?:\/\//) ? url : 'http://' + url;
Note that you'll need to use the SSL protocol sometimes, so this is not a complete solution.
I made small changes function form answered by iMoses which worked for me.
Check for both https OR http protocol
if (!url.match(/^http?:\/\//i) || !url.match(/^https?:\/\//i)) {
url = 'http://' + url;
}
Hope it make more accurate for other situation !

How can I get everything after the forward slash in my url?

When I visit my url, my script will get the current URL and store it in a variable with
var currentURL = (document.URL);
I'd like to get everything after the forward slash in my url because there will be a hash ID after the forward slash like this:
www.mysite.com/XdAs2
so this is what would be stored in my variable currentURL and I'd like to take only the XdAs2 from it and store that into another variable. In addition, I'd like to know two other things.
Is document.URL the best way to get the current URL or will I have issues with some browsers?
If I were to try to open that URL using an iframe, will document.URL still work? or must there be an address bar present containing the url? I would really appreciate answers for those questions three questions. Thank you
Here's some pseudo code:
var currentURL = (document.URL); // returns http://myplace.com/abcd
var part = currentURL.split("/")[1];
alert(part); // alerts abcd
Basically:
1) document.URL should work fine in all major browsers. For more info refer to this Mozilla Developer Network article or this SO question
2) for an iframe, you need to write something like: document.getElementById("iframe_ID").src.toString()
Using jquery, you can do he following in order to access every inch of the current URL:
www.mysite.com/XdAs2?x=123
assuming you have the following url:
1- get the url in a jQuery object
var currentUrl = $(location)
2- access everything using the following syntax
var result = currentUrl.attr('YOUR_DESIRED_PROPERTY');
some common properties:
hostname => www.mysite.com
pathname => XdAs2
search => ?x=123
I hope this may help.
If you want everything after the host, use window.location.pathname
Following on from Mohammed's answer you can do the same thing in vanilla javascript:
var urlPath = location.pathname,
urlHost = location.hostname;

Javascript help needed with bookmark

Hey I have this little javascript bookmark
javascript:(function(){ window.open('http://www.mywebsite.com/index.php?currentsite#bookmark'); })()
How can I get the url of the current website into that url?
I have heard of using document.URL But I am not sure how to get that into the URL in the bookmark with the URL of the site currently browsing. Meaning at the moment the result is http://www.mywebsite.com/index.php?currentsite=document.URL#bookmark
Thanks
javascript:(function(){ window.open('http://www.mywebsite.com/index.php?currentsite=' + encodeURIComponent(location.href) + '#bookmark'); })()
try
window.location or document.location.href or window.location.href
I forgot which one works :)
Try using this instead:
javascript:( function(){window.open('http://www.mywebsite.com/index.php?'+document.location.href+'#bookmark');} )()
Just use window.location.href - like this:
window.open( 'http://<someurl>?' + window.location.href + '#somebookmark' );
window.location.href will give you the href of current frame.
I'm not exactly sure what you are talking about but if you are trying to get the full URL along with the anker you can document.location.href http://www.w3schools.com/jsref/prop_doc_url.asp
You can access the parts of the URL using Location Object http://www.w3schools.com/jsref/obj_location.asp
your code should look like this:
function(){
var url = document.location.href;
window.open('http://www.mywebsite.com/index.php?currentsite = ' + url);
}
Not sure if thats what you where trying to do.

Get relative path of the page url using javascript

In javascript, how can I get the relative path of the current url?
for example http://www.example.com/test/this?page=2
I want just the /test/this?page=2
Try
window.location.pathname+window.location.search
location.href
holds the url of the page your script is running in.
The quickest, most complete way:
location.href.replace(/(.+\w\/)(.+)/,"/$2");
location.href.replace(location.origin,'');
Only weird case:
http://foo.com/ >> "/"
You can use the below snippet to get the absolute url of any page.
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
}
})();
// Sample Result based on the input.
getAbsoluteUrl('/'); //Returns http://stackoverflow.com/
Checkout get absolute URL using Javascript for more details and multiple ways to achieve the same functionality.
I use this:
var absURL = document.URL;
alert(absURL);
Reference: http://www.w3schools.com/jsref/prop_doc_url.asp
You should use it the javascript way, to retrieve the complete path including the extensions from the page,
$(location).attr('href');
So, a path like this, can be retrieved too.
www.google.com/results#tab=2

Categories

Resources