History object
The History object saves the URLs of all pages visited in the current window. For security reasons, browsers do not allow scripts to read these addresses, but allow navigation between addresses. The "forward" and "back" buttons on the browser toolbar actually operate on the History object.
If the anchor value of the URL (hash) is changed, a browsing record will also be created in the History object.
Attribute history.
length
: The number of URLs visited in the current window (including the current web page).state
: The state value of the top layer of the History stack. It is usuallyundefined
, that is, it is not set.
Method history.
back()
: Move to the previous URL, which is equivalent to clicking the back button of the browser. For the first URL visited, this method has no effect.forward()
: Move to the next URL, which is equivalent to clicking the browser’s forward button. For the last URL visited, this method has no effect.go()
: Accept an integer as a parameter, and move to the URL specified by the parameter based on the current URL. For example,go(1)
equivalent toforward()
, andgo(-1)
equivalent toback()
. If the parameter exceeds the actual URL range, this method has no effect; if no parameter is specified, the default parameter is0
, which is equivalent to refreshing the current page.pushState()
: Used to add a record in the history. It will not trigger a page refresh, just cause the History object to change, and the address bar will respond. IfpushState
sets a new anchor value (ie, hash), thehashchange
event will not be triggered.replaceState()
: Used to modify the current record of the History object, andpushState()
is exactly the same as the 060d554d3572b2 method.
event
popstate
: Whenever the browsing history (history object) of the same document changes, thepopstate
event will be triggered. Just calling thepushState()
orreplaceState()
method will not trigger the event. It will only be triggered when the user clicks the browser back button and the forward button, or uses JavaScript to call thehistory.back()
,history.forward()
, orhistory.go()
methods.
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
attributes, you can get this object.
Attributes
href
: The entire URL.protocol
: The protocol of the current URL, including the colon:
.host
: host. If the port is not the default 80 and 433 of the protocol, the colon:
and the port will also be included.hostname
: host name, excluding port.port
: Port number.pathname
: The path part of the URL, starting from the root path/
.search
: The query string part, starting from the question mark?
.hash
: Fragment string part, starting from#
.username
: The user name in front of the domain name.password
: The password in front of the domain name.origin
: The protocol, host name and port of the URL.
// 当前网址为 http://user:passwd@www.example.com:4097/path/a.html?x=111#part1
location.protocol // "http:"
location.host // "www.example.com:4097"
location.hostname // "www.example.com"
location.port // "4097"
location.pathname // "/path/a.html"
location.search // "?x=111"
location.hash // "#part1"
location.username // "user"
location.password // "passwd"
location.origin // "http://user:passwd@www.example.com:4097"
Among these attributes, only the origin attribute is read-only, and other attributes are writable.
Note that if you href
, the browser will immediately jump to this new address. It is often used to automatically scroll a web page to a new anchor point.
location.href = '#top';
// 等同于
location.hash = '#top';
URL encoding and decoding
The URL of the web page can only contain legal characters. Legal characters are divided into two categories:
- URL meta-characters: semicolon
;
, comma,
, slash/
, question mark?
, colon:
, at@
,&
, equal sign=
, plus sign+
,$
,#
- Semantic character:
a-z
,A-Z
,0-9
, conjunctions number-
, underlined_
, point.
, exclamation!
, wavy lines~
, asterisk*
, single quotes'
, parentheses()
.
In addition to the above characters, all other characters in the URL must be escaped, and each byte must be converted to a percent sign %
plus two uppercase hexadecimal letters.
URL encoding/decoding method
JavaScript provides four URL encoding/decoding methods:
encodeURI()
: 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.encodeURIComponent()
: 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.decodeURI()
: Used for decoding the entire URL. It is the inverse operationencodeURI()
It accepts one parameter, which is the URL after transcoding.decodeURIComponent()
: Used to decode URL fragments. It is the inverse operationencodeURIComponent()
It accepts one parameter, which is the URL fragment after transcoding.
URL constructor
new URL(input[, base])
: Create a new URL object by parsing input
relative to base
input
: The absolute or relative URL to be parsed. Ifinput
is a relative path,base
is required. Ifinput
is an absolute path,base
is ignored.base
: Ifinput
is not an absolute path, it is the base URL to be parsed.
url object
The properties of the URL instance are basically the same as those of the Location object, and return information about the current URL.
url.href
: return the entire URLurl.protocol
: return the agreement, ending:
url.hostname
: return the domain nameurl.host
: returns the domain name and port, including:
, the default80
and443
ports will be omittedurl.port
: return porturl.origin
: return protocol, domain name and porturl.pathname
: return path, starting/
url.search
: Returns the query string, starting?
url.searchParams
: returns anURLSearchParams
, which is not available in the Location objecturl.hash
: Returns the fragment identifier, starting with the hash sign#
url.password
: Return the password in front of the domain nameurl.username
: Returns the user name in front of the domain name
URLSearchParams object
URLSearchParams
object is a native object of the browser, 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 ?
question mark 060d554d357c6a does not matter, or it can be an array or object corresponding to the query string.
// 方法一:传入字符串
let params = new URLSearchParams('?foo=1&bar=2');
// 等同于
let params = new URLSearchParams(document.location.search);
// 方法二:传入数组
let params = new URLSearchParams([['foo', 1], ['bar', 2]]);
// 方法三:传入对象
let params = new URLSearchParams({'foo' : 1 , 'bar' : 2});
Instance method
toString()
: Returns the string form of the instance.append()
: 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. Does not recognize whether the key name already exists.let params = new URLSearchParams('?foo=1&bar=2'); params.toString() // "foo=1&bar=2' params.append('foo', 3); params.toString() // "foo=1&bar=2&foo=3"
delete()
: Used to delete the specified query parameters. Accept the key name as a parameter.params.delete('bar');
set()
: used to set the 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. If there are multiple keys with the same name, set will remove the duplicate keys and leave only one.get()
: Used to read the specified key in the query string. Accept the key name as a parameter. 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 isnull
. If there are multiple keys with the same name,get
returns the key value at the top of the position.getAll()
: Returns an array, the members are all the key values of the specified key. Accept the key name as a parameter.sort()
: Sort the keys, the rule is to arrange the Unicode code points from small to large. There is no return value. If there are two keys with the same name, they will not be sorted, but the original order will be preserved.keys()
: What is returned is the iterator of the key name.values()
: What is returned is the iterator of the key value.entries()
: What is returned is the iterator of key-value pairs.forEach()
: Traverse each key-value pair.
let params = new URLSearchParams('a=3&b=6')
params.forEach((value, key, params)=>{
console.log(value, key); // 3 a // 6 b
})
for (const name of params.keys()) {
console.log(name); // a b
}
for (const name of params.values()) {
console.log(name); // 3 6
}
for (const name of params.entries()) {
console.log(name); // ['a', '3'] ['b', '6']
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。