티스토리 뷰
반응형
자바스크립트 현재 url 알아보기
JavaScript를 사용하여 현재 URL(Uniform Resource Locator)을 가져오는 방법은 window.location 객체를 사용하는 것입니다. window.location 객체는 현재 문서에 대한 정보를 제공하는 JavaScript 객체입니다. window.location 객체는 다음과 같은 속성들을 가지고 있습니다.
- 1. window.location.href: 현재 페이지의 전체 URL을 반환합니다.
- 2. window.location.protocol: 현재 페이지의 프로토콜(http: 또는 https:)을 반환합니다.
- 3. window.location.host: 현재 페이지의 호스트(도메인)를 반환합니다.
- 4. window.location.hostname: 현재 페이지의 호스트(도메인) 이름을 반환합니다.
- 5. window.location.port: 현재 페이지의 포트 번호를 반환합니다.
- 6. window.location.pathname: 현재 페이지의 경로를 반환합니다.
- 7. window.location.search: 현재 페이지의 쿼리 문자열을 반환합니다.
- 8. window.location.hash: 현재 페이지의 해시 값을 반환합니다.
1. window.location.href
var currentUrl = window.location.href;
2. window.location.protocol
var currentUrl = window.location.protocol + '//' + window.location.host + window.location.pathname;
3. window.location.host
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://' + window.location.host + '/api/data', true);
xhr.send();
4. window.location.hostname
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://' + window.location.hostname + '/api/data', true);
xhr.send();
5. window.location.port
if (window.location.protocol === 'https:' && window.location.port === '') {
// HTTPS 기본 포트를 사용하는 경우
} else if (window.location.protocol === 'http:' && window.location.port === '') {
// HTTP 기본 포트를 사용하는 경우
} else {
// 기본 포트가 아닌 경우
}
6. window.location.pathname
var path = window.location.pathname;
7. window.location.search
var queryString = window.location.search;
var params = new URLSearchParams(queryString);
var id = params.get('id'); // "123"
var name = params.get('name'); // "John"
8. window.location.hash
var tabs = document.querySelectorAll('.tab');
tabs.forEach(function(tab) {
tab.addEventListener('click', function(event) {
var hash = event.target.hash;
window.location.hash = hash;
});
});
window.addEventListener('hashchange', function(event) {
var hash = window.location.hash;
var tab = document.querySelector(hash);
// 선택한 탭으로 변경
});
반응형
댓글