JavaScript/생활코딩

웹브라우저 자바스크립트 - Location객체

점미 2018. 11. 22. 15:33



Location객체 - https://opentutorials.org/course/1375/6634



Location객체 - 현재 브라우저창에 문서의url을 알려주는 객체




URL에 대한 정보 확인


F12를 눌러 콘솔창에서 아래의 코드를 입력하면 현재 url을 알려준다.

location.toString()과 location.href 둘다 같은 결과를 출력한다.

실제로는 location.href를 더 많이 사용하고 있다.


console.log(location.toString(), location.href);




Location객체를 사용하여 url의 여러가지 정보를 알아낼 수 있다.


console.log(location.protocol) - http, https 둘 중 하나를 반환한다.

console.log(location.host) - 도메인을 반환한다

console.log(location.port) - 도메인뒤에 포트를 반환한다. 없으면 아무것도 반환하지 않는다

console.log(location.pathname) - 도메인뒤에 구체적인 정보이다

console.log(location.search) - ?부터 그 뒤 내용의 어떠한 정보를 반환한다

console.log(location.hash) - #부터 그 위 내용의 어떠한 정보를 반환한다





URL변경


코드들은 콘솔에 입력하여 바로 확인할 수도 있고, html파일에서 자바스크립트안에 넣어서 실행시킬 수도 있다.


사용자를 다른url로 이동시켜야 할 경우 사용된다.

location.href = 'http://egoing.net';



웹페이지의 내용을 리로드 할 때 사용된다.

location.reload();