URL API - Web APIs 编辑

The URL API is a component of the URL standard, which defines what constitutes a valid Uniform Resource Locator and the API that accesses and manipulates URLs. The URL standard also defines concepts such as domains, hosts, and IP addresses, and also attempts to describe in a standard way the legacy application/x-www-form-urlencoded MIME type used to submit web forms' contents as a set of key/value pairs.

Note:

This feature is available in Web Workers.

URL concepts and usage

The majority of the URL standard is taken up by the definition of a URL and how it is structured and parsed. Also covered are definitions of various terms related to addressing of computers on a network, and the algorithms for parsing IP addresses and DOM addresses are specified. More interesting to most developers is the API itself.

Accessing URL components

Creating an URL object for a given URL parses the URL and provides quick access to its constituent parts through its properties.

let addr = new URL("https://developer.mozilla.org/wiki/en-US/docs/Web/API/URL_API");
let host = addr.host;
let path = addr.pathname;

The snippet above creates a URL object for the article you're reading right now, then fetches the host and pathname properties. In this case, those strings are developer.mozilla.org and /wiki/en-US/docs/Web/API/URL_API, respectively.

Changing the URL

Most of the properties of URL are settable; you can write new values to them to alter the URL represented by the object. For example, to create a URL and set its username:

let myUsername = "someguy";
let addr = new URL("https://mysite.com/login");
addr.username = myUsername;

Setting the value of username not only sets that property's value, but it updates the overall URL. After executing the code snippet above, the value returned by addr.href is https://someguy@mysite.com/login. This is true for any of the writable properties.

Queries

The search property on a URL contains the query string portion of the URL. For example, if the URL is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. You can also look up the values of individual parameters with the URLSearchParams object's get() method:

let addr = new URL("https://mysite.com/login?user=someguy&page=news");
try {
  loginUser(addr.searchParams.get("user"));
  gotoPage(addr.searchParams.get("page"));
} catch(err) {
  showErrorMessage(err);
}

For example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site.

Other functions within URLSearchParams let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.

URL API interfaces

The URL API is a simple one, with only a couple of interfaces to its name:

Older versions of the specification included an interface called URLUtilsReadOnly, which has since been merged into the WorkerLocation interface.

Examples

If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a URL object to do it for you. The fillTableWithParameters() function below takes as input a HTMLTableElement object representing a <table>. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value.

Note the call to URLSearchParams.sort() to sort the parameter list before generating the table.

function fillTableWithParameters(tbl) {
  let url = new URL(document.location.href);
  url.searchParams.sort();
  let keys = url.searchParams.keys();

  for (let key of keys) {
    let val = url.searchParams.get(key);
    let row = document.createElement("tr");
    let cell = document.createElement("td");
    cell.innerText = key;
    row.appendChild(cell);
    cell = document.createElement("td");
    cell.innerText = val;
    row.appendChild(cell);
    tbl.appendChild(row);
  };
}

A working version of this example can be found on Glitch. Just add parameters to the URL when loading the page to see them in the table. For instance, try https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable.

Specifications

SpecificationStatusComment
URLLiving StandardWHATWG specification

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:112 次

字数:7941

最后编辑:6年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文