I have a page that is available on address below
http://localhost/foo/test/index.html
and
http://localhost/foo/test
(without back slash)
I can place a css file in the parent directory (http://localhost/foo/test/style.css
) and add it on the page with
<link rel = "stylesheet" href = "../style.css" />
and browser will successfully load the style sheet.
If we look at window.location
, it's http://localhost/foo/test/index.html
on the first reference and http://localhost/foo/test
on the second reference (i.e. we have an additional path element in the end of the first url and don't have it in the second one).
How does a browser know, that he should make a request to http://localhost/foo/style.css
to get style sheet content in both cases?
And how can I get this base url with client-side javascript (or know that test
is a directory and not a file)?
For example if I want to know that requests to http://localhost/foo/style.css
and ../style.css
are the same.
Notice: I can't use server side code for it.
UPD: There is an error in the question. Browser doesn't correctly load the style sheet from url without a slash on the end. Thank you!
CodePudding user response:
Not a full answer for sure but on JS side try window.location object
window.location.href
returns the href (URL) of the current page
window.location.hostname
returns the domain name of the web host
window.location.pathname
returns the path and filename of the current page
window.location.protocol
returns the web protocol used (http: or https:)
window.location.assign()
loads a new document
source: https://www.w3schools.com/js/js_window_location.asp
CodePudding user response:
You can get base URL of current site by using JavaScript window Object
console.log(window.location.origin)
//gives the current url