Location object, URL object, URLSearchParams object

Location object, URL object, URLSearchParams object

URL is one of the infrastructure of the Internet. The browser provides some native objects to manage URLs.

Location Object

The Location object is a native object provided by the browser and provides URL-related information and operation methods. Through the window.location and document.location properties, you can get this object.

Attributes

The Location object provides the following attributes.

-Location.href: The entire URL. -Location.protocol: The protocol of the current URL, including the colon (:). -Location.host: host. If the port is not the default 80 and 433 of the protocol, a colon (:) and port will also be included. -Location.hostname: host name, excluding port. -Location.port: Port number. -Location.pathname: The path part of the URL, starting from the root path /. -Location.search: The part of the query string, starting from the question mark ?. -Location.hash: Fragment string part, starting from #. -Location.username: The username in front of the domain name. -Location.password: The password in front of the domain name. -Location.origin: the protocol, host name and port of the URL.

// The current URL is
// http://user:passwd@www.example.com:4097/path/a.html?x=111#part1
document.location.href;
// "http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
document.location.protocol;
// "http:"
document.location.host;
// "www.example.com:4097"
document.location.hostname;
// "www.example.com"
document.location.port;
// "4097"
document.location.pathname;
// "/path/a.html"
document.location.search;
// "?x=111"
document.location.hash;
// "#part1"
document.location.username;
// "user"
document.location.password;
// "passwd"
document.location.origin;
// "http://user:passwd@www.example.com:4097"

Among these attributes, only the origin attribute is read-only, and all other attributes are writable.

Note that if you write a new URL address to Location.href, the browser will immediately jump to this new address.

// Jump to the new URL
document.location.href = "http://www.example.com";

This feature is often used to automatically scroll a web page to a new anchor point.

document.location.href = "#top";
// Equivalent to
document.location.hash = "#top";

Rewriting location directly is equivalent to writing the href attribute.

document.location = "http://www.example.com";
// Equivalent to
document.location.href = "http://www.example.com";

In addition, the Location.href property is the only property that the browser allows for cross-domain writing, that is, a non-same-origin window can overwrite the Location.href property of another window (such as a child window and a parent window), causing the latter URL redirect. Other attributes of Location are not allowed to be written across domains.

Method

(1) Location.assign()

The assign method accepts a URL string as a parameter, which makes the browser immediately jump to the new URL. If the parameter is not a valid URL string, an error will be reported.

// Jump to the new URL
document.location.assign("http://www.example.com");

(2) Location.replace()

The replace method accepts a URL string as a parameter, causing the browser to jump to the new URL immediately. If the parameter is not a valid URL string, an error will be reported.

The difference between it and the assign method is that replace will delete the current URL in the browser’s browsing history History, that is to say, once this method is used, the back button cannot return to the current webpage, which is equivalent to In the browsing history, the old URL is replaced with the new URL. One of its applications is that when the script finds that it is a mobile device, it immediately jumps to the mobile version of the web page.

// Jump to the new URL
document.location.replace("http://www.example.com");

(3) Location.reload()

The reload method makes the browser reload the current URL, which is equivalent to pressing the browser's refresh button.

It accepts a Boolean value as a parameter. If the parameter is true, the browser will request this webpage from the server again, and after reloading, the webpage will scroll to the head (ie scrollTop === 0). If the parameter is false or empty, the browser will reload the webpage from the local cache, and after reloading, the viewport position of the webpage is the position before reloading.

// Re-request the current URL from the server
window.location.reload(true);

(4) Location.toString()

The toString method returns the entire URL string, which is equivalent to reading the Location.href property.

URL encoding and decoding

The URL of the web page can only contain legal characters. Legal characters are divided into two categories.

-URL metacharacters: semicolon (;), comma (,), slash (/), question mark (?), colon (:), at (@), &, equal sign (=), plus sign (+), dollar sign ($), pound sign (#) -Semantic characters: az, AZ, 0-9, hyphen (-), underscore (_), dot (.), exclamation mark (!), tilde ( ~), asterisk (*), single quote ('), parenthesis (())

In addition to the above characters, all other characters in the URL must be escaped. The rule is to convert each byte to a percent sign (%) plus two uppercase hexadecimals according to the default encoding of the operating system letter.

For example, on a UTF-8 operating system, in the URL of http://www.example.com/q=春节, the Chinese character "春节" is not a legal character in the URL, so it is automatically converted to http: by the browser. //www.example.com/q=%E6%98%A5%E8%8A%82. Among them, "Spring" is converted to %E6%98%A5, and "Jest" is converted to %E8%8A%82. This is because the UTF-8 encodings of "Spring" and "Section" are E6 98 A5 and E8 8A 82 respectively. Adding a percent sign in front of each byte constitutes the URL encoding.

JavaScript provides four URL encoding/decoding methods.

-encodeURI() -encodeURIComponent() -decodeURI() -decodeURIComponent()

encodeURI()

The encodeURI() method is used to transcode the entire URL. Its parameter is a string representing the entire URL. It will escape characters other than metacharacters and semantic characters.

encodeURI("http://www.example.com/q=春节");
// "http://www.example.com/q=%E6%98%A5%E8%8A%82"

encodeURIComponent()

The encodeURIComponent() method is used to transcode the components of the URL. All characters except semantic characters will be transcoded, that is, metacharacters will also be transcoded. Therefore, it cannot be used to transcode the entire URL. It accepts one parameter, which is a fragment of the URL.

encodeURIComponent("Spring Festival");
// "%E6%98%A5%E8%8A%82"
encodeURIComponent("http://www.example.com/q=春节");
// "http%3A%2F%2Fwww.example.com%2Fq%3D%E6%98%A5%E8%8A%82"

In the above code, encodeURIComponent() will escape URL meta-characters together, so if you transcode the entire URL, an error will occur.

decodeURI()

The decodeURI() method is used to decode the entire URL. It is the inverse operation of the encodeURI() method. It accepts one parameter, which is the URL after transcoding.

decodeURI("http://www.example.com/q=%E6%98%A5%E8%8A%82");
// "http://www.example.com/q=Spring Festival"

decodeURIComponent()

decodeURIComponent() is used to decode URL fragments. It is the inverse operation of the encodeURIComponent() method. It accepts one parameter, which is the URL fragment after transcoding.

decodeURIComponent("%E6%98%A5%E8%8A%82");
// "Spring Festival"

URL interface

The browser natively provides the URL() interface, which is a constructor function used to construct, parse and encode URLs. Under normal circumstances, this constructor can be obtained through window.URL.

Constructor

URL() is used as a constructor to generate URL instances. It accepts a string representing the URL as a parameter. If the parameter is not a valid URL, an error will be reported.

var url = new URL("http://www.example.com/index.html");
url.href;
// "http://www.example.com/index.html"

The above example generates a URL instance to represent the specified URL.

In addition to strings, the parameter of URL() can also be another URL instance. At this time, URL() will automatically read the href attribute of the instance as the actual parameter.

If the URL string is a relative path, the second parameter representing the absolute path is required as the calculation basis.

var url1 = new URL("index.html", "http://example.com");
url1.href;
// "http://example.com/index.html"

var url2 = new URL("page2.html", "http://example.com/page1.html");
url2.href;
// "http://example.com/page2.html"

var url3 = new URL("..", "http://example.com/a/b.html");
url3.href;
// "http://example.com/"

In the above code, the path of the returned URL instance is obtained by switching to the first parameter on the basis of the second parameter. In the last example, the first parameter is .., indicating the upper path.

Instance attributes

The attributes of the URL instance are basically the same as those of the Location object, and return the information of the current URL.

-URL.href: return the entire URL -URL.protocol: return the protocol, ending with a colon : -URL.hostname: return the domain name -URL.host: return the domain name and port, including the : number, the default port 80 and 443 will be omitted -URL.port: return port -URL.origin: return protocol, domain name and port -URL.pathname: return path, start with slash / -URL.search: Returns the query string, starting with a question mark ? -URL.searchParams: returns an instance of URLSearchParams, this attribute is not available in the Location object -URL.hash: Returns the fragment identifier, starting with the hash sign # -URL.password: return the password in front of the domain name -URL.username: returns the username in front of the domain name

var url = new URL(
  "http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
);

url.href;
// "http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
url.protocol;
// "http:"
url.hostname;
// "www.example.com"
url.host;
// "www.example.com:4097"
url.port;
// "4097"
url.origin;
// "http://www.example.com:4097"
url.pathname;
// "/path/a.html"
url.search;
// "?x=111"
url.searchParams;
// URLSearchParams {}
url.hash;
// "#part1"
url.password;
// "passwd"
url.username;
// "user"

Among these attributes, only the origin attribute is read-only, other attributes are writable, and will take effect immediately.

var url = new URL("http://example.com/index.html#part1");

url.pathname = "index2.html";
url.href; // "http://example.com/index2.html#part1"

url.hash = "#part2";
url.href; // "http://example.com/index2.html#part2"

In the above code, changing the pathname attribute and hash attribute of the URL instance will be reflected in the URL instance in real time.

Static method

(1) URL.createObjectURL()

The URL.createObjectURL() method is used to generate a URL string for uploaded/downloaded files and streaming media files. This string represents the URL of the File object or the Blob object.

// HTML code is as follows
// <div id="display"/>
// <input
// type="file"
// id="fileElem"
// multiple
// accept="image/*"
// onchange="handleFiles(this.files)"
//>
var div = document.getElementById("display");

function handleFiles(files) {
  for (var i = 0; i < files.length; i++) {
    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(files[i]);
    div.appendChild(img);
  }
}

In the above code, the URL.createObjectURL() method is used to generate a URL string for the uploaded file as the source of the image of the <img> element.

The URL generated by this method looks like the following.

blob: http://localhost/c745ef73-ece9-46da-8f66-ebes574789b1

Note that every time you use the URL.createObjectURL() method, a URL instance will be generated in the memory. If the URL string generated by this method is no longer needed, in order to save memory, you can use the URL.revokeObjectURL() method to release this instance.

(2) URL.revokeObjectURL()

The URL.revokeObjectURL() method is used to release the URL instance generated by the URL.createObjectURL() method. Its parameter is the URL string returned by the URL.createObjectURL() method.

Add URL.revokeObjectURL() to the example in the previous paragraph below.

var div = document.getElementById("display");

function handleFiles(files) {
  for (var i = 0; i < files.length; i++) {
    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(files[i]);
    div.appendChild(img);
    img.onload = function () {
      window.URL.revokeObjectURL(this.src);
    };
  }
}

In the above code, once the image is loaded successfully, the URL string generated for the local file is useless, so you can use the URL.revokeObjectURL() method to uninstall this URL instance in the img.onload callback function.

URLSearchParams object

Overview

The URLSearchParams object is the browser's native object, used to construct, parse and process the query string of the URL (that is, the part after the URL question mark).

It is also a constructor in itself, which can generate instances. The parameter can be a query string, the initial question mark ? does not matter, or it can be an array or object corresponding to the query string.

// Method 1: Pass in a string
var params = new URLSearchParams("?foo=1&bar=2");
// Equivalent to
var params = new URLSearchParams(document.location.search);

// Method 2: Pass in an array
var params = new URLSearchParams([
  ["foo", 1],
  ["bar", 2],
]);

// Method 3: Pass in the object
var params = new URLSearchParams({ foo: 1, bar: 2 });

URLSearchParams will automatically encode the query string.

var params = new URLSearchParams({ foo: "Hello" });
params.toString(); // "foo=%E4%BD%A0%E5%A5%BD"

In the above code, the value of foo is a Chinese character, and URLSearchParams will automatically URL encode it.

When the browser sends form data to the server, it can directly use the URLSearchParams instance as the form data.

const params = new URLSearchParams({foo: 1, bar: 2});
fetch('https://example.com/api', {
  method:'POST',
  body: params
}).then(...)

In the above code, when the fetch command sends a command to the server, you can directly use the URLSearchParams instance.

URLSearchParams can be used in conjunction with the URL() interface.

var url = new URL(window.location);
var foo = url.searchParams.get("foo") || "somedefault";

In the above code, the searchParams property of the URL instance is an instance of URLSearchParams, so the get method of the URLSearchParams interface can be used.

The URLSearchParams instance has an iterator interface, which can be traversed with for...of (see the "Iterator" chapter of "Introduction to ES6 Standards" for details).

var params = new URLSearchParams({ foo: 1, bar: 2 });

for (var p of params) {
  console.log(p[0] + ": " + p[1]);
}
// foo: 1
// bar: 2

URLSearchParams has no instance attributes, only instance methods.

URLSearchParams.toString()

The toString method returns the string form of the instance.

var url = new URL("https://example.com?foo=1&bar=2");
var params = new URLSearchParams(url.search);

params.toString(); // "foo=1&bar=2'

When a string is needed, the toString method is automatically called.

var params = new URLSearchParams({ version: 2.0 });
window.location.href = location.pathname + "?" + params;

In the above code, when assigning a value to location.href, you can directly use the params object. At this time, the toString method is automatically called.

URLSearchParams.append()

The append() method is used to append a query parameter. It accepts two parameters, the first is the key name, the second is the key value, and there is no return value.

var params = new URLSearchParams({ foo: 1, bar: 2 });
params.append("baz", 3);
params.toString(); // "foo=1&bar=2&baz=3"

The append() method does not recognize whether the key name already exists.

var params = new URLSearchParams({ foo: 1, bar: 2 });
params.append("foo", 3);
params.toString(); // "foo=1&bar=2&foo=3"

In the above code, foo already exists in the query string, but append will still append a key with the same name.

URLSearchParams.delete()

The delete() method is used to delete the specified query parameters. It accepts key names as parameters.

var params = new URLSearchParams({ foo: 1, bar: 2 });
params.delete("bar");
params.toString(); // "foo=1"

URLSearchParams.has()

The has() method returns a boolean value indicating whether the query string contains the specified key name.

var params = new URLSearchParams({ foo: 1, bar: 2 });
params.has("bar"); // true
params.has("baz"); // false

URLSearchParams.set()

The set() method is used to set the key value of the query string.

It accepts two parameters, the first is the key name, and the second is the key value. If it is an existing key, the key value will be overwritten, otherwise it will be appended.

var params = new URLSearchParams("?foo=1");
params.set("foo", 2);
params.toString(); // "foo=2"
params.set("bar", 3);
params.toString(); // "foo=2&bar=3"

In the above code, foo is a key that already exists, and bar is a key that does not yet exist.

If there are multiple keys with the same name, set will remove all existing keys.

var params = new URLSearchParams("?foo=1&foo=2");
params.set("foo", 3);
params.toString(); // "foo=3"

The following is an example of replacing the current URL.

// URL: https://example.com?version=1.0
var params = new URLSearchParams(location.search.slice(1));
params.set("version", "2.0");

window.history.replaceState({}, "", location.pathname + `?` + params);
// URL: https://example.com?version=2.0

URLSearchParams.get(), URLSearchParams.getAll()

The get() method is used to read the specified key in the query string. It accepts key names as parameters.

var params = new URLSearchParams("?foo=1");
params.get("foo"); // "1"
params.get("bar"); // null

Two places need attention. First, it returns a string. If the original value is a numeric value, you need to change the type; second, if the specified key name does not exist, the return value is null.

If there are multiple keys with the same name, get returns the value of the first key in the position.

var params = new URLSearchParams("?foo=3&foo=2&foo=1");
params.get("foo"); // "3"

In the above code, the query string has three foo keys, and the get method returns the first key value 3.

The getAll() method returns an array, the members are all the key values ​​of the specified key. It accepts key names as parameters.

var params = new URLSearchParams("?foo=1&foo=2");
params.getAll("foo"); // ["1", "2"]

In the above code, the query string has two foo keys, and the array returned by getAll has two members.

URLSearchParams.sort()

The sort() method sorts the keys in the query string. The rule is to sort the keys in Unicode code points from smallest to largest.

This method has no return value, or the return value is undefined.

var params = new URLSearchParams("c=4&a=2&b=3&a=1");
params.sort();
params.toString(); // "a=2&a=1&b=3&c=4"

In the above code, if there are two keys a with the same name, they will not be sorted between them, but the original order will be retained.

URLSearchParams.keys(), URLSearchParams.values(), URLSearchParams.entries()

These three methods all return an iterator object for for...of to loop through. The difference between them is that the keys method returns the iterator of the key name, the values method returns the iterator of the key-value, and the entries returns the iterator of the key-value pairs.

var params = new URLSearchParams("a=1&b=2");

for (var p of params.keys()) {
  console.log(p);
}
// a
// b

for (var p of params.values()) {
  console.log(p);
}
// 1
// 2

for (var p of params.entries()) {
  console.log(p);
}
// ["a", "1"]
// ["b", "2"]

If you traverse the URLSearchParams directly, the internal call is actually the entries interface.

for (var p of params) {
}
// Equivalent to
for (var p of params.entries()) {
}