这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
URL() 构造函数返回一个新创建的URL对象,表示由参数定义的URL。
如果给定的基本URL或生成的URL不是有效的URL,则会抛出一个类型为SYNTAX_ERROR的DOMException。
语法
const url = new URL(urlString, [baseURLstring]) const url = new URL(urlString, baseURLobject)
参数
- urlString
- 是一个表示绝对或相对URL的
DOMString。如果urlString是相对URL,则baseURLstring或baseURLobject(无论存在)都将用作基本URL。如果urlString是绝对URL,则将忽略baseURLstring和baseURLobject。 - baseURLstring 可选
- 是一个表示基本URL的
DOMString,以便在urlString是相对URL时使用。如果未指定,且在参数中未传递baseURLobject,则默认为“about:blank”。如果它是一个无效的绝对URL,构造函数将引发一个类型为SYNTAX_ERROR的DOMException - baseURLobject
- 是表示基本URL的
URL对象,以便在urlString是相对URL时使用。
Example
var a = new URL("/", "https://developer.mozilla.org"); // Creates a URL pointing to 'https://developer.mozilla.org/'
var b = new URL("https://developer.mozilla.org"); // Creates a URL pointing to 'https://developer.mozilla.org'
var c = new URL('en-US/docs', b); // Creates a URL pointing to 'https://developer.mozilla.org/en-US/docs'
var d = new URL('/en-US/docs', b); // Creates a URL pointing to 'https://developer.mozilla.org/en-US/docs'
var f = new URL('/en-US/docs', d); // Creates a URL pointing to 'https://developer.mozilla.org/en-US/docs'
var g = new URL('/en-US/docs', "https://developer.mozilla.org/fr-FR/toto");
// Creates a URL pointing to 'https://developer.mozilla.org/en-US/docs'
var h = new URL('/en-US/docs', a); // Creates a URL pointing to 'https://developer.mozilla.org/en-US/docs'
var i = new URL('/en-US/docs', ''); // Raises a SYNTAX ERROR exception as '/en-US/docs' is not valid
var j = new URL('/en-US/docs'); // Raises a SYNTAX ERROR exception as 'about:blank/en-US/docs' is not valid
var k = new URL('http://www.example.com', 'https://developers.mozilla.com');
// Creates a URL pointing to 'https://www.example.com'
var l = new URL('http://www.example.com', b); // Creates a URL pointing to 'https://www.example.com'
Specification
| Specification | Status | Comment |
|---|---|---|
| URL URL.URL() |
Living Standard | Initial definition. |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | 26.0 (26.0) | 未实现 | ? | ? |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | 26.0 (26.0) | 未实现 | ? | ? |
See also
- The interface it belongs to:
URL.