Location

Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the Document and Window interface have such a linked Location , accessible via Document.location and Window.location 分别。

位置的解剖

HTML

<span id="href" title="href"><span id="protocol" title="protocol">http:</span>//<span id="host" title="host"><span id="hostname" title="hostname">example.org</span>:<span id="port" title="port">8888</span></span><span id="pathname" title="pathname">/foo/bar</span><span id="search" title="search">?q=baz</span><span id="hash" title="hash">#bang</span></span>
					

CSS

html, body {height:100%;}
html {display:table; width:100%;}
body {display:table-cell; text-align:center; vertical-align:middle; font-family:georgia; font-size:230%; line-height:1em; white-space:nowrap;}
[title] {position:relative; display:inline-block; box-sizing:border-box; /*border-bottom:.5em solid;*/ line-height:2em; cursor:pointer;}
[title]:before {content:attr(title); font-family:monospace; position:absolute; top:100%; width:100%; left:50%; margin-left:-50%; font-size:40%; line-height:1.5; background:black;}
[title]:hover:before,
:target:before {background:black; color:yellow;}
[title] [title]:before {margin-top:1.5em;}
[title] [title] [title]:before {margin-top:3em;}
[title]:hover,
:target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);}
					

JavaScript

[].forEach.call(document.querySelectorAll('[title][id]'), function (node) {
  node.addEventListener("click", function(e) {
    e.preventDefault();
    e.stopPropagation();
    window.location.hash = '#' + $(this).attr('id');
  });
});
[].forEach.call(document.querySelectorAll('[title]'), function (node) {
  node.addEventListener("click", function(e) {
    e.preventDefault();
    e.stopPropagation();
    window.location.hash = '';
  });
});
					

结果

特性

Location.ancestorOrigins
是静态 DOMStringList containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given Location 对象。
Location.href
Is a stringifier that returns a USVString containing the entire URL. If changed, the associated document navigates to the new page. It can be set from a different origin than the associated document.
Location.protocol
USVString 包含 URL 的协议方案,包括最终的 ':' .
Location.host
USVString 包含主机,即 hostname ':' ,和 port of the URL.
Location.hostname
USVString 包含 URL 的域。
Location.port
USVString 包含 URL 的端口号。
Location.pathname
USVString 包含初始 '/' followed by the path of the URL.
Location.search
USVString 包含 '?' followed by the parameters or "querystring" of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring.
Location.hash
USVString 包含 '#' followed by the fragment identifier of the URL.
Location.origin 只读
返回 USVString containing the canonical form of the origin of the specific location.

方法

Location.assign()
Loads the resource at the URL provided in parameter.
Location.reload()
重新加载当前 URL,像刷新按钮。
Location.replace()
Replaces the current resource with the one at the provided URL (redirects to the provided URL). The difference from the assign() method and setting the href property is that after using replace() the current page will not be saved in session History , meaning the user won't be able to use the back button to navigate to it.
Location.toString()
返回 USVString containing the whole URL. It is a synonym for HTMLHyperlinkElementUtils.href , though it can't be used to modify the value.

范例

// Create anchor element and use href property for the purpose of this example
// A more correct alternative is to browse to the URL and use document.location or window.location
var url = document.createElement('a');
url.href = 'https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container';
console.log(url.href);      // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
console.log(url.protocol);  // https:
console.log(url.host);      // developer.mozilla.org:8080
console.log(url.hostname);  // developer.mozilla.org
console.log(url.port);      // 8080
console.log(url.pathname);  // /en-US/search
console.log(url.search);    // ?q=URL
console.log(url.hash);      // #search-results-close-container
console.log(url.origin);    // https://developer.mozilla.org:8080
					

规范

规范 状态 Comment
HTML Living Standard
The definition of 'Location' in that specification.
实时标准

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Location Chrome 1 Edge 12 Firefox 1 IE 3 Opera 3 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0
ancestorOrigins Chrome 20 Edge 79 Firefox No IE No Opera 15 Safari 6 WebView Android 4.4 Chrome Android 25 Firefox Android No Opera Android 14 Safari iOS 6 Samsung Internet Android 1.5
assign Chrome 1 Edge 12 Firefox 1 IE 5.5 Opera 3 Safari 3 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0
hash Chrome Yes Edge 12 Firefox 22 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
host Chrome Yes Edge 12 Firefox 22 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
hostname Chrome Yes Edge 12 Firefox 22 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
href Chrome Yes Edge 12 Firefox 22 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
origin Chrome Yes Edge 12 Firefox 26
26
Before Firefox 49, results for URL using the blob scheme incorrectly returned null.
IE 11
11
Intranet sites are set to Compatibility View, which will emulate IE7 and omit window.location.origin .
Opera 10 Safari Yes
Yes
According to Apple's documentation , window.location.origin is supported since Safari 10 (both desktop and mobile), but the feature seems to be present in some older versions as well. Because of this, the exact versions supporting this feature cannot be determined reliably.
WebView Android Yes Chrome Android Yes Firefox Android 26
26
Before Firefox 49, results for URL using the blob scheme incorrectly returned null.
Opera Android ? Safari iOS 5 Samsung Internet Android Yes
password
弃用 非标
Chrome No Edge No Firefox 26 — 45 IE No Opera No Safari No WebView Android No Chrome Android No Firefox Android 26 — 45 Opera Android No Safari iOS No Samsung Internet Android No
pathname Chrome Yes Edge 12 Firefox 22
22
Before Firefox 53, the pathname property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, pathname would return "/x?a=true&b=false" rather than "/x".
IE Yes
Yes
Internet Explorer does not provide the leading slash character in the pathname ( docs/Web/API/Location instead of /docs/Web/API/Location ).
Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22
22
Before Firefox 53, the pathname property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, pathname would return "/x?a=true&b=false" rather than "/x".
Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
port Chrome Yes Edge 12 Firefox 22 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
protocol Chrome Yes Edge 12 Firefox 22 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
reload Chrome 1 Edge 12
12
Before Edge 79, if a page added to Trusted Sites contains a cross-origin iframe, then calling reload() from within the iframe reloads the trusted page (in other words, the top page reloads, not the iframe).
Firefox 1 IE 5.5
5.5
If a page added to Trusted Sites contains a cross-origin iframe, then calling reload() from within the iframe reloads the trusted page (in other words, the top page reloads, not the iframe).
Opera 3 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0
replace Chrome 1 Edge 12 Firefox 1 IE 5.5 Opera 3 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0
search Chrome Yes Edge 12 Firefox 22
22
Before Firefox 53, the search property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, search would return "", rather than "?a=true&b=false".
IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 22
22
Before Firefox 53, the search property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, search would return "", rather than "?a=true&b=false".
Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
toString Chrome 52 Edge 12 Firefox 22 IE 11
11
Intranet sites are set to Compatibility View, which will emulate IE7 and omit window.location.toString .
Opera ? Safari ? WebView Android 52 Chrome Android 52 Firefox Android 22 Opera Android ? Safari iOS ? Samsung Internet Android 6.0
username
弃用 非标
Chrome No Edge No Firefox 26 — 45 IE No Opera No Safari No WebView Android No Chrome Android No Firefox Android 26 — 45 Opera Android No Safari iOS No Samsung Internet Android No

图例

完整支持
完整支持
不支持
不支持
兼容性未知
兼容性未知
非标。预期跨浏览器支持较差。
非标。预期跨浏览器支持较差。
弃用。不要用于新网站。
弃用。不要用于新网站。
见实现注意事项。

另请参阅

  1. Location
  2. 特性
    1. Location: ancestorOrigins
    2. Location: hash
    3. Location: host
    4. Location: hostname
    5. Location: href
    6. Location: origin
    7. Location: password
    8. Location: pathname
    9. Location: port
    10. Location: protocol
    11. Location: search
    12. Location: username
  3. 方法
    1. Location: assign()
    2. Location: reload()
    3. Location: replace()
    4. Location: toString()
  4. Related pages for HTML DOM
    1. BeforeUnloadEvent
    2. DOMStringMap
    3. ErrorEvent
    4. GlobalEventHandlers
    5. HTMLAnchorElement
    6. HTMLAreaElement
    7. HTMLAudioElement
    8. HTMLBRElement
    9. HTMLBaseElement
    10. HTMLBaseFontElement
    11. HTMLBodyElement
    12. HTMLButtonElement
    13. HTMLCanvasElement
    14. HTMLContentElement
    15. HTMLDListElement
    16. HTMLDataElement
    17. HTMLDataListElement
    18. HTMLDialogElement
    19. HTMLDivElement
    20. HTMLDocument
    21. HTMLElement
    22. HTMLEmbedElement
    23. HTMLFieldSetElement
    24. HTMLFormControlsCollection
    25. HTMLFormElement
    26. HTMLFrameSetElement
    27. HTMLHRElement
    28. HTMLHeadElement
    29. HTMLHeadingElement
    30. HTMLHtmlElement
    31. HTMLIFrameElement
    32. HTMLImageElement
    33. HTMLInputElement
    34. HTMLIsIndexElement
    35. HTMLKeygenElement
    36. HTMLLIElement
    37. HTMLLabelElement
    38. HTMLLegendElement
    39. HTMLLinkElement
    40. HTMLMapElement
    41. HTMLMediaElement
    42. HTMLMetaElement
    43. HTMLMeterElement
    44. HTMLModElement
    45. HTMLOListElement
    46. HTMLObjectElement
    47. HTMLOptGroupElement
    48. HTMLOptionElement
    49. HTMLOptionsCollection
    50. HTMLOutputElement
    51. HTMLParagraphElement
    52. HTMLParamElement
    53. HTMLPictureElement
    54. HTMLPreElement
    55. HTMLProgressElement
    56. HTMLQuoteElement
    57. HTMLScriptElement
    58. HTMLSelectElement
    59. HTMLShadowElement
    60. HTMLSourceElement
    61. HTMLSpanElement
    62. HTMLStyleElement
    63. HTMLTableCaptionElement
    64. HTMLTableCellElement
    65. HTMLTableColElement
    66. HTMLTableDataCellElement
    67. HTMLTableElement
    68. HTMLTableHeaderCellElement
    69. HTMLTableRowElement
    70. HTMLTableSectionElement
    71. HTMLTemplateElement
    72. HTMLTextAreaElement
    73. HTMLTimeElement
    74. HTMLTitleElement
    75. HTMLTrackElement
    76. HTMLUListElement
    77. HTMLUnknownElement
    78. HTMLVideoElement
    79. HashChangeEvent
    80. History
    81. ImageData
    82. MessageChannel
    83. MessageEvent
    84. MessagePort
    85. Navigator
    86. NavigatorGeolocation
    87. NavigatorID
    88. NavigatorLanguage
    89. NavigatorOnLine
    90. NavigatorPlugins
    91. PageTransitionEvent
    92. Plugin
    93. PluginArray
    94. PopStateEvent
    95. PortCollection
    96. PromiseRejectionEvent
    97. RadioNodeList
    98. Transferable
    99. ValidityState
    100. Window
    101. WindowBase64
    102. WindowEventHandlers
    103. WindowTimers