Is possible to create instance of Location?
Attempting to use Location
to manipulate arbitrary URIs will not work as desired. The Location
object/type is not a general URI container, but is rather a special contract with the DOM and its navigation state.
I found this URI JavaScript type by webr3 via google, YMMV:
URI Type for javascript
- Supports all kinds of URI (URL, URN, any scheme).
- Relative URI Resolution
- All classes extend the native String implementation.
- Pure ECMA-262 implementation of URI spec (RFC-3986)
- Works Client or Server side, (V8 / node.js compatible).
No, you can't. A browser window has one instance of window
and a window has one location
. Trying to create multiple instances of window
or window.location
would seem indicative of conceptual errors.
If I'm understanding what you want to do correctly, you should create an anchor
element manipulate that with javascript:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;
alert('protocol: ' + protocol);
alert('hash: ' + hash);
Or, if you already have an anchor, you can use
var url = document.getElementById('myanchorid');
Though the question is quite old, posting the answer anyway as using native HTML Web APIs is considered to be a good practice.
Solution
- The HTML Web API URL allows us to create a URL object which has following properties in it.
- The typescript equivalent of this object looks like this -
interface URL {
hash: string;
host: string;
hostname: string;
href: string;
readonly origin: string;
password: string;
pathname: string;
port: string;
protocol: string;
search: string;
username: string;
readonly searchParams: URLSearchParams;
toString(): string;
}
Example
As an example,
var url = new URL('http://localhost:8081/route1/route2?q=test#route3/route4');
Gives you following object-
{
hash: "#route3/route4"
host: "localhost:8081"
hostname: "localhost"
href: "http://localhost:8081/route1/route2?q=test#route3/route4"
origin: "http://localhost:8081"
password: ""
pathname: "/route1/route2"
port: "8081"
protocol: "http:"
search: "?q=test"
searchParams: URLSearchParams {}
username: ""
}
Compatibility Check
Check the compatibility before using.
I hope this solution is useful for you.