Location Object Detailed Explanation

location object

location is one of the most useful BOM objects, it provides information about the document loaded in the current window, and also provides some navigation functions. It is both the window object and the property of the document object, that is, window.location and document.location refer to the same object. Its main functions are as follows:

  1. Save the information of the current document
  2. navigation function
  3. parsing URLs

Attributes

attribute name example illustrate
hash #contents Return the path of the hash pattern in the url, that is, 0 or a string after the #, if the url is not a hash pattern, return an empty string
host www.wrox.com:80 Returns the server and port name
hostname www.wrox.com Returns the server name without the port number
href http://www.wrox.com Return the complete url, location.toString() returns this object
pathname “/file/” Returns the directory or file name in the URL
port 8080 return port number
protocol http: Return protocol, usually http or https
search ?=javascript Returns the URL query string, generally ending with ? beginning

example

Take Nuggets Address ( https://juejin.cn/search?query=async await&type=0 ) as an example, you can see locationthe returned parameters

insert image description here

query string parameters

Although all subsequent query parameters location.searchwill be returned , they are always in the form of strings, and there is no way to parse the query parameters.?

location.searchThe parameter generation rules for are as follows:

  1. splicing &parameter
  2. format isname=value
  3. use encodeURIComponent()encryption

To do this, you can create a parsing parameter function according to the rules generated by URL query parameters , as follows:

function getQueryStringArgs() {
    // 取得要查询的字符串并去掉开头的问号
    var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
        args = {},
        items = qs.length ? qs.split("&"): [],
        item = null,
        name = null,
        value = null,
        //  在for 循环中使用
        i = 0,
        len = items.length;

    // 逐个将每一项目添加到args对象中
    for (i; i < len; i++) {
        item = items[i].split("=");
        name = decodeURIComponent(item[0]);
       value = decodeURIComponent(items[1]);
        if (name.length) {
            args[name] = value
        }
    }
    console.log(args);
    return args;
}

Trample record

I found such a passage in mdn

Modern browsers provide [URLSearchParams](https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams/get#examples)and [URL.searchParams](https://developer.mozilla.org/zh-CN/docs/Web/API/URL/searchParams#examples)interface to make it easier to parse query parameters from query strings.

But they all have a note below:

insert image description here

So in fact, using these two functions in the console cannot parse out the query parameters, as follows:
insert image description here

location manipulation

Jump— location.assign()

Changing the browser location, the main usage is location.assign(url), it will probably return the following three results:

  1. Trigger the window to load and display the content urlof
  2. When the current locationand urlare not of the same origin, a SECURITY_ERRORTypeError
  3. When an invalid one is passed in url, a SYNTAX_ERRORtype

replace— location.replace()

Replace the current resource. Unlike [assign()](https://developer.mozilla.org/zh-CN/docs/Web/API/Location/assign)the method , replace()after calling the method, the current page will not be saved in the session history, that is, the back button cannot be clicked to go back

// 语法
object.replace(url);

// 示例
object.replace('http://www.baidu.com');

other

You can change the currently loaded page by modifying locationother properties of the object, such as href, hash, search, pathnameetc.

// 将url改为http://baidu.com
location.href = 'http://baidu.com';

// 改为http://baidu.com/#section
location.hash = '#section';

// 改为http://baidu.com/?keyword=css
location.search = '?keyword=css';

// 改为http://baidu.com/mydir
location.pathname = 'mydir';

// 改为https://juejin.cn/
location.hostname='juejin.cn'

// 将端口改为8080
location.port = '8080'

**Note:** Every time locationa property is modified ( hashexcept), the page will be refreshed
insert image description here

Refresh the page — location.reload()

To refresh the current page in the most efficient way, the main rules are as follows:

  1. When the page has not changed since the last request, the page is reloaded from the browser cache
  2. If the page has changed, reload it from the server

This is mainly request headerto judge whether it is updated or not. For details, refer to the article on browser cache knowledge combing

If you need to force a refresh, you can uselocation.reload(true)

**Note:** location.reload()The code after the call may not be executed, depending on factors such as network latency or system resources. Therefore, it is best to location.reload()place the last line

location.toString()

stringReturn **the entire url address in the form of ,** as follows :
insert image description here

Guess you like

Origin blog.csdn.net/weixin_41886421/article/details/129452674