url属性

335 阅读1分钟

参考资料

1. hash

var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/href#Examples');
url.hash // Returns '#Examples'

2. host

var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/host');
var result = url.host // "developer.mozilla.org"

var url = new URL('https://developer.mozilla.org:443/en-US/docs/Web/API/URL/host');
var result = url.host // "developer.mozilla.org"
// The port number is not included because 443 is the scheme's default port

var url = new URL('https://developer.mozilla.org:4097/en-US/docs/Web/API/URL/host');
var result = url.host // "developer.mozilla.org:4097"

3. hostname

var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname');
var result = url.hostname; // Returns:'developer.mozilla.org'

4. href

var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/href');
var result = url.href; // Returns: 'https://developer.mozilla.org/en-US/docs/Web/API/URL/href'

5. origin

origin属性返回URL的协议,主机名和端口号

// 假设当前的URL是https://www.jc2182.com:4088/test.htm#part2
var x = location.origin;
// https://www.jc2182.com:4098

6. pathname

包含一个初始 '/' 和URL的路径(如果没有路径,则为空字符串)

var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname');
var result = url.pathname; // Returns:"/en-US/docs/Web/API/URL/pathname"

7. port

var url = new URL('https://mydomain.com:80/svn/Repos/');
var result = url.port; // Returns:'80'

8. protocol

var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol');
var result = url.protocol; // Returns:"https:"

9. search

是一个搜索字符串, 也称为查询字符串,这是一个USVString包含一个 '?'后面跟着URL的参数

var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/search?q=123');
var queryString = url.search; // Returns:"?q=123"

10. searchParams

用于访问url中的查询参数。比如http://localhost?a=1&b=2,searchParams等于{a: 1, b: 2}

// 当前url是https://example.com/?name=Jonathan&age=18
let params = (new URL(document.location)).searchParams;
let name = params.get("name"); // "Jonathan"
let age = parseInt(params.get("age")); // 18

浏览器禁用回退

<script language="javascript">
    //防止页面后退
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
            history.pushState(null, null, document.URL);
    });
</script>