特殊协议


WHATWG URL 标准认为少数 URL 协议规范在解析和序列化方面具有特殊性。 使用这些特殊协议之一解析 URL 时, url.protocol 属性可能会被更改为其他特殊协议,但不能更改为非特殊协议,反之亦然。

例如,从 http 更改为 https 工作如下:

const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org

但是,从 http 更改为假设的 fish 议并不是因为新协议并不特殊。

const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org

同样,也不允许从非特殊协议更改为特殊协议:

const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org

根据 WHATWG URL 标准,特殊协议规范是 ftpfilegopherhttphttpswswss

The WHATWG URL Standard considers a handful of URL protocol schemes to be special in terms of how they are parsed and serialized. When a URL is parsed using one of these special protocols, the url.protocol property may be changed to another special protocol but cannot be changed to a non-special protocol, and vice versa.

For instance, changing from http to https works:

const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org

However, changing from http to a hypothetical fish protocol does not because the new protocol is not special.

const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org

Likewise, changing from a non-special protocol to a special protocol is also not permitted:

const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org

According to the WHATWG URL Standard, special protocol schemes are ftp, file, gopher, http, https, ws, and wss.