URL() constructor returns a newly created URL object representing the URL defined by the parameters.

If the given base URL or the resulting URL are not valid URLs, the JavaScript TypeError exception is thrown.

注意: 此特征可用于 Web 工作者 .

句法

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

参数

url
USVString representing an absolute or relative URL. If url is a relative URL, base is required, and will be used as the base URL. If url is an absolute URL, a given base 将被忽略。
base 可选
USVString representing the base URL to use in case url is a relative URL. If not specified, it defaults to '' .

注意 : You can still use an existing URL 对象为 base , which stringifies itself to the object's href 特性。

异常

异常 解释
TypeError url (in the case of absolute URLs) or base + url (in the case of relative URLs) is not a valid URL.

范例

// Base urls
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
The definition of 'URL.URL()' in that specification.
实时标准 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
URL() 构造函数 Chrome 19 Edge 12 Firefox 26 IE No Opera 15 Safari 6 WebView Android ≤37 Chrome Android 25 Firefox Android 26 Opera Android 14 Safari iOS 6 Samsung Internet Android 1.5

图例

完整支持

完整支持

不支持

不支持

另请参阅

  • The interface it belongs to: URL .

元数据

  • 最后修改: