Web APIs中Location、URL和URLSearchParams介面
阿新 • • 發佈:2018-11-10
1 Location Interface
The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to.
- Properties
let l = document.location
document.location === window.location // true
// 等價
document.location = "https://www.csdn.net"
document.location.href = "https://www.csdn.net"
// 賦值後頁面跳轉
l.href // http://localhost:8088/one.html?a=1&b=2#map
l.protocol // http:
l.host // localhost:8088
l.hostname // localhost
l.port // 8088
l.pathname // /one.html
l.search // ?a=1&b=2
l.hash // #map, 仍在當前頁面, 會跳到文件中相應位置
l.origin // http://localhost:8088, 賦值無效
// mozilla開發文件中有此屬性, 在chrome中測試不存在
l.username // undefined
l.password // undefined
- Methods
let l = document.location
l.toString() // l.href的同義詞(synonym)
l.reload(true) // 從伺服器reload
l.reload() // 從快取或者伺服器reload
l.assign("http://www.csdn.net") // 新增到History
l.replace("http://www.csdn.net") // 不新增到History
2 URL Interface
The URL interface represents an object providing static methods used for creating object URLs.
When using a user agent where no constructor has been implemented yet, it is possible to access such an object using the Window.URL properties (prefixed with Webkit-based browser as Window.webkitURL).
// IE不支援,其他瀏覽器也有版本要求
let url = new URL("http://foo:[email protected]:8088/one.html?a=1&b=2")
// 在chrome中測試
url.username // foo, 沒有則為empty string
url.password // bar, 沒有則為empty string
url.URLSearchParams // URLSearchParams例項,只讀
// 其他properties同location,沒有methods
3 URLSearchParams Interface
The URLSearchParams interface defines utility methods to work with the query string of a URL.
- Constructor
// 注意:IE不支援,其他瀏覽器也要求較高版本,所有methods都是Experiment APIs
// 以下方法等價
let s = new URLSearchParams("?a=1&b=2") // 最前面的?會被忽略
let s = new URLSearchParams("a=1&b=2")
let s = new URLSearchParams([["a", 1], ["b", 2]])
let s = new URLSearchParams({a: 1, b: 2})
- Methods
s.has("a") // true
s.forEach((v, k, o) => console.log(v, k, o))
// 1 a s, 2 b s
s.append("a", 11)
s.get("a") // 1, 返回第一個,沒有則返回null
s.getAll("a") // [1, 11]
// 返回Iterator物件
[...s.keys()] // ["a", "b", "a"]
[...s.values()] // [1, 2, 11]
[...s.entries()] // [["a", 1], ["b", 2], ["a", 11]]
s.sort() // 按key升序排序
[...s.keys()] // ["a", "a", "b"]
s.set("c", 3) // 相當於append
s.set("a", 1) // 只剩下一個"a"
[...s.keys()] // ["a", "b"]
s.delete("a") // 刪除所有的"a"
參考:
https://developer.mozilla.org/en-US/docs/Web/API/location
https://developer.mozilla.org/en-US/docs/Web/API/URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams