10 minutes to review the Location object

The Location object contains information about the current URL. It is a special object because it is part of the Window object and can be accessed through the window.location property. Is also a property of the Document object, which is used by document.location.

My path is http://127.0.0.1:5501/html/index.html? page Id =123#test, type window.location on the console, and return a location object.

Some of these are properties, some of these are methods, so let’s look at them briefly.

Object properties

Let’s look at some of these properties in terms of the Location object expanded in the figure above

attribute describe
hash Anchor point section to#At the beginning
host Host name + port number
hostname The host name Such as127.0.0.1 localhost
href Contains the full URL
origin Protocol + host name + port number
pathname Path section to/At the beginning
port Port, common80 443Etc.
protocol The protocol for the URL, and notice there’s one at the end:, such ashttp: https:
search Parameter section, to?At the beginning

The following is an example on MDN, which shows the contents of each part clearly and intuitively:

The above attributes, in addition to Origin is a read-only attribute can not be modified, the rest of the attributes are both read and write. How do properties get and set

console.log(window.location.hash)  // Read the hash result of the current page as #test
window.location.hash = 'test2' // Set the hash of the current page to observe that the browser URL changes
console.log(window.location.hash) // Read the hash again and the result is #test2
window.location.href = 'https://www.baidu.com'  // The page jumps directly to Baidu
Copy the code

By the way, most browsers now support the Hashchange event. This event is triggered when the content after the browser # changes.

window.addEventListener('hashchange', () = > {console.log('Hash has changed')})Copy the code

After executing the code above, the console will print a prompt when we change the hash part of the URL. Of course, for browsers that are not compatible with hashchange events, there are ways to simulate this, such as setting a timer to look up the current hash at regular intervals and compare it to the previous hash to determine whether the HASH in the URL has changed. Note: Every time you change the location property (except hash), the page reloads with the new URL.

Supplementary case

There was a requirement in the project to click a button to copy a registration link with a personal invitation code. As this way: https://www.xx.com/register?code=8888. So this link needs us to splice. My original pseudocode is as follows

let inviteCode = 8888
let url = location.origin + '/register? code' + inviteCode
copy(url)
Copy the code

But later the test students told me that there was a problem in the compatibility test. There was a problem with the path copied from the browser below IE11. The location. Origin attribute does not exist in Internet Explorer 10 and below, so it returns undefined. The solution code is as follows:

if(! location.origin){ location.origin = location.protocol +'/ /' + location.hostname + (location.port ? ':'+location.port : ' ')}let inviteCode = 8888
let url = location.origin + '/register? code' + inviteCode
copy(url)
Copy the code

Submit the code, so the test students happily told me that the problem was solved.

Object methods

As you can see from the diagram at the beginning of this article, the Location object has three methods (not to mention the toString method, which returns a string containing the full URL)

methods describe
assign Loading a new page
reload Reload the current page
replace Replace the current page with a new one

Here is to explain the usage and difference of these several methods. First we talked about the Reload method. The parameter to this method is an optional Boolean type. If left blank, the default is false, indicating that the current page refresh may be read from the cache, equivalent to a normal F5 refresh. True means that the browser is forced to retrieve page resources from the server, equivalent to a forcible refresh (Shift+F5 or Cmd+Shift+R)

window.location.reload()  // The current page is reloaded after execution
Copy the code

Then there are the assign and replace methods, both of which require passing in a parameter that represents the address of the new page. The difference is that with assign, you leave the address of the previous page in the browser’s history, and can return to the previous page when you hit the back button on the new page. Replace is to replace the address of the old page with the address of the new page, and then click the back button to go back to our previous page. Open a new blank page, execute the following code separately on the console, and click the back button in the upper left corner of the browser to see what happens.

// Open two new blank pages, each executing one line of code
window.location.assign('https://www.baidu.com')
window.location.replace('https://www.baidu.com')
Copy the code

As mentioned in MDN,Location is actually an interface that represents the URL of the object to be linked to.Document and Window interfaces both have such a linked Location. So we can access the location object either through document.location or window.location. Even location is a global variable. If we type location directly into the console, it will also return a Location object

The meta attribute enables refreshing and jumping

The timer +location method is not necessary when we want to jump to a page or refresh the current page every once in a while. We can also use the meta attribute to achieve the same effect. Suppose I have a monitor page and want to refresh the page every 20 seconds. The method code for using the timer is as follows:

setTimeout((a)= > {
    window.location.reload()
},20000)
Copy the code

Using meta tags requires only that

<meta http-equiv="refresh" content="20"/>
Copy the code

If this is a simple introduction page, it will almost automatically jump to another page after 10 seconds. We can also use the meta attribute above. Just add the jump address after the time in the content and it will automatically jump when the time is up.

<meta http-equiv="refresh" content="10; https://www.baidu.com"/>
Copy the code

The downside of using meta is that the refresh and jump cannot be cancelled. Therefore, its usage scenario depends on the specific business. For example, a page that requires permission is accessed illegally, so you can automatically jump to other pages after a certain amount of time.

Gets the query string in the URL

Many times, there is a need to get the value of a key in the URL query string. For example, in a such as http://127.0.0.1:5501/html/index.html? Id =123&name=zhangsan obtain the value of ID, that is, 123. So there are a number of ways we can do this.

The traditional method

function getUrlQuery(){
  let url = window.location.search
  let obj = Object.create(null)
  if(url.includes('? ')) {let str = url.substr(1)
    let strs = str.split('&')
    for(let i = 0; i < strs.length; i++){let tmp = strs[i].split('=')
        obj[decodeURIComponent(tmp[0=]]decodeURIComponent(tmp[1])}}return obj
}
Copy the code

Note that decodeURIComponent is used in the above code to decode, since query strings are usually encoded by encodeURIComponent,

URLSearchParams interface

const urlParams = new URLSearchParams(window.location.search)
console.log(urlParams.get('id'))  / / 123
Copy the code

The URLSearchParams interface defines some useful methods for handling query strings in urls. Here is its specific introduction, interested students can have a look, we will not expand first.

conclusion

Actually, there’s not a lot of knowledge about the Location object. The little Red Book is just three pages long. It’s also often mentioned as part of the BOM along with the Navigator and History object, but we’ll talk about that later.