반응형
개요
개인 프로젝트 중 JavaScript로 redirect를 할 수 있는 방법을 찾다가, Javascirpt의 location 객체를 통해 다양한 방법으로 URL 페이지를 관리할 수 있다는 것을 알게되었다.
Location 객체 프로퍼티
1. href
현재 페이지 URL 전체를 나타낸다.
location.href = "<https://foobar.com>"
href를 사용해 페이지를 이동하려면 꼭 URL origin을 넣어 할당해야 한다. 그렇지 않으면 현재 페이지에서 요청하게 된다.
// 현재 페이지: <https://foobar.com>
location.href = "google.com"
// 변경 후: <https://google.com/google.com>
2. protocol
현재 URL의 protocol을 나타낸다.
location.protocol // http: OR https:
3. host
현재 URL의 hostname:PORT
location.host // foobar.com:8080
4. hostname
현재 URL의 hostname
location.host // foobar.com
5. port
URL port 정보 (port가 URL에 명시되어 있지 않으면 빈 값)
location.port // 8080
6. path
hostname 뒤에 따라오는 path
// <https://foobar.com/foo/bar>
location.path // /foo/bar
7. search
파라미터 부분
// <https://foobar.com/search?foo=bar>
location.search // ?foo=bar
8. hash
#와 #뒤에 따라오는 부분 타겟이 될 페이지의 아이디이다.
// <https://foobar.com/#foobar>
location.hash // #foobar
9. origin
URL의 origin
// <https://foobar.com/foo/bar/search?foobar>
location.origin // <https://foobar.com>
location 객체 메소드
1. assign
값으로 넣은 URL로 redirect History session 관리가 된다.
location.assign("/");
2. replace
assign과 비슷한 기능이지만 history session 관리가 안된다 (뒤로가기 불가능).
location.replace("/");
3. reload
현재 페이지에서 refresh true -> 서버에서 부터 새로고침 false -> 캐쉬에서 부터 새로고침 (default)
location.reload(); // = location.reload(false);
location.reload(true)
4. toString
URL을 String으로 반환
// <https://foobar.com>
location.toString(); // "<https://foobar.com>"
반응형
'JavaScript' 카테고리의 다른 글
[JavaScript] json에서 -(dash)가 포함된 key에 접근하는 방법 (0) | 2024.03.01 |
---|