Window.location Cheatsheet

window.location Cheatsheet

원문: https://dev.to/samanthaming/window-location-cheatsheet-4edl

window.location cheatsheet

웹사이트의 URL정보를 찾는 중이라면, window.location이 바로 당신이 찾는 객체이다. 현재 페이지의 주소에 관한 정보를 찾거나 페이지 리다이렉트 또는 새로고침을 하고자 한다면 이 프로퍼티를 사용해라.

https://www.samanthaming.com/tidbits/?filter=JS#2

window.location.origin   → 'https://www.samanthaming.com/tidbits/?filter=JS#2'
               .protocol → 'https:'
               .host     → 'www.samanthaming.com'
               .hostname → 'www.samanthaming.com'
               .port     → ''
               .pathname → '/tidbits/'
               .search   → '?filter=JS'
               .hash     → '#2'
               .href     → 'https://www.samanthaming.com/tidbits/?filter=JS#2'
window.location.assign('url')
               .replace('url')
               .reload()
               .toString()

window.location 프로퍼티들

window.location Returns
.origin Base URL(프로토콜 + 호스트명 + 포트번호)
.protocol 프로토콜 스키마(http: 또는 https)
.host 도메인명 + 포트
.hostname 도메인명
.port 포트번호
.pathname 처음 / 다음에 오는 경로
.search ? 다음에 오는 쿼리 스트링
.hash # 다음에 오는 앵커 또는 플래그먼트 식별자
.href 전체 URL

hosthostname 간의 차이

나의 위 예시에서 당신은 hosthostname가 같은 값을 반환한다는 것을 알았다. 그럼 이 두 프로퍼티는 왜 따로 존재할까? 음, 차이는 포트번호를 다루는 데 있다. 이를 살펴보자.

포트정보가 없는 URL

https://www.samanthaming.com

window.location.host; // 'www.samanthaming.com'
window.location.hostname; // 'www.samanthaming.com'

window.location.port; // ''

포트정보가 있는 URL

https://www.samanthaming.com:8080

window.location.host; // 'www.samanthaming.com:8080'
window.location.hostname; // 'www.samanthaming.com'

window.location.port; // '8080'

그러니까 host는 포트번호를 포함할 것이다. 반면에, hostname은 호스트명만 반환할 것이다.

URL 프로퍼티들을 바꾸는 법

location 프로퍼티를 사용해 URL 정보만 얻을 수 있는 것은 아니다. 새 프로퍼티값들을 입력해 URL을 변경하는 데도 사용할 수 있다. 내가 무슨 말을 했는 지 살펴보자.

// START 'www.samanthaming.com'

window.location.pathname = '/tidbits'; // pathname을 설정했다.

// RESULT 'www.samanthaming.com/tidbits'

값을 바꿀 수 있는 프로퍼티 목록은 다음과 같다.

// 예
window.location.protocol = 'https'
               .host = 'localhost:8080'
               .hostname = 'localhost'
               .port = '8080'
               .pathname = 'path'
               .search = 'query string' // (?가 필요없다)
               .hash = 'hash' // (#가 필요없다)
               .href = 'url'

변경할 수 없는 유일한 프로퍼티는 window.location.origin이다. 이 값은 읽기만 가능하다.

Location 객체

window.locationLocation 객체를 반환한다. 이는 페이지의 현제 위치에 대한 정보를 제공한다. 그런데 이 Location 객체에 접근하는 방법은 다양하다.

window.location          → Location
window.document.location → Location
document.location        → Location
location                 → Location

이렇게 할 수 있는 까닭은 이것들이 브라우저의 전역 변수이기 때문이다.

전역변수 location과 document

window.location vs location

이 4가지 프로퍼티는 모두 같은 Location 객체를 가리킨다. 나는 개인적으로 window.location을 선호한다. 그리고 사실 location 사용을 꺼려한다. 기본저긍로 location은 매우 일반적인 용어처럼 읽히고, 다른 사람이 실수로 그들의 변수명으로 지정하여 전역 변수를 오버라이드할 수 있다.

// https://www.samanthaming.com

location.protocol; // 'https'

function localFile() {
  const location = '/sam';

  return location.protocol;
  // ❌ undefined
  //    지역변수 "location"이 전역변수를 오버라이드했기 때문이다.
}

나는 대부분의 개발자들이 window가 전역 변수라는 것을 알고 있다고 생각한다. 그러므로 혼란을 주지 않을까 거의 걱정하지 않아도 된다. 솔직히 말하면, 나는 location이 전역변수인지 이 포스트를 쓰기 전까지 몰랐다 😅. 그래서 나는 window.location을 사용해서 좀더 명시적으로 표현하는 것을 추천한다 👍.

다음은 내 개인적인 선호이다.

// ✅
1. window.location   // 🏆
2. document.location

// ❌
3. window.document.location //  그냥 #1 이나 #2를 쓰는 게 어떨까 😅
4. location // 너무 모호하게 느껴진다 😵

물론, 이는 단지 나의 선호도일 뿐이다. 당신은 당신의 코드베이스의 전문가이고, 가장 좋은 방법은 존재하지 않으며, 가장 좋은 방법은 항상 당신과 당신의 팀에 가장 적절한 방법이다.

window.location 메서드들

window.location  
.assign() 주어진 URL로 이동한다
.replace() 주어진 URL로 이동한다. 그리고 현재 페이지를 세션 히스토리에서 제거한다.
.reload() 현재 페이지를 리로드한다
.toString() URL을 반환한다

window.location.toString

MDN에는 이렇게 정의되어 있다.

이 메서드는 URL의 USVString을 반환한다. 이 것은 Location.href의 읽기전용버전이다.

즉, href 값을 얻는 데 이를 사용할 수 있다.

// https://www.samanthaming.com

window.location.href; // https://www.samanthaming.com
window.location.toString(); // https://www.samanthaming.com