URL()

URL() 构造函数返回一个新创建的 URL 对象,表示由一组参数定义的 URL。

如果给定的基本 URL 或生成的 URL 不是有效的 URL 链接,则会抛出一个TypeError

Note: 此特性在 Web Worker 中可用。

语法

const url = new URL(url [, base])

参数

url
是一个表示绝对或相对 URL 的 DOMString。如果url 是相对 URL,则会将 base 用作基准 URL。如果 url 是绝对URL,则无论参数url是否存在,都将被忽略。
base 可选
是一个表示基准 URL 的 DOMString,在 url 是相对 URL 时,它才会起效。如果未指定,则默认为 ''

异常

异常 解释
TypeError url若为绝对 URL)或 base + url(若为相对 URL)是一个无效的 URL 链接。

示例

let m = 'https://developer.mozilla.org';
let a = new URL("/", m);                                // => 'https://developer.mozilla.org/'
let b = new URL(m);                                     // => 'https://developer.mozilla.org/'

        new URL('en-US/docs', b);                      // => 'https://developer.mozilla.org/en-US/docs'
let d = new URL('/en-US/docs', b);                     // => 'https://developer.mozilla.org/en-US/docs'
        new URL('/en-US/docs', d);                     // => 'https://developer.mozilla.org/en-US/docs'
        new URL('/en-US/docs', a);                     // => 'https://developer.mozilla.org/en-US/docs'
        
        new URL('/en-US/docs', "https://developer.mozilla.org/fr-FR/toto");
                                                       // => 'https://developer.mozilla.org/en-US/docs'
                                                       
        new URL('/en-US/docs', '');                    // Raises a TypeError exception as '' is not a valid URL
        new URL('/en-US/docs');                        // Raises a TypeError exception as '/en-US/docs' is not a valid URL
        new URL('http://www.example.com', );           // => 'http://www.example.com/'
        new URL('http://www.example.com', b);          // => 'http://www.example.com/'

        new URL("//foo.com", "https://example.com")    // => 'https://foo.com' (see relative URLs)

规范

规范 状态 备注
URL
URL.URL()
Living Standard Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
URL() constructorChrome Full support 19Edge Full support 12Firefox Full support 26IE No support NoOpera Full support 15Safari Partial support 6
Notes
Partial support 6
Notes
Notes In Safari 14 and earlier, calling the URL constructor with a base URL whose value is undefined causes Safari to throw a TypeError; see WebKit bug 216841.
WebView Android Full support ≤37Chrome Android Full support 25Firefox Android Full support 26Opera Android Full support 14Safari iOS Partial support 6
Notes
Partial support 6
Notes
Notes In Safari 14 and earlier, calling the URL constructor with a base URL whose value is undefined causes Safari to throw a TypeError; see WebKit bug 216841.
Samsung Internet Android Full support 1.5

Legend

Full support  
Full support
Partial support  
Partial support
No support  
No support
See implementation notes.
See implementation notes.

参见