JavaScript의 Location origin 속성은 현재 페이지 URL에서 프로토콜(protocol), 호스트명(hostname), 그리고 포트 번호(port, 지정된 경우에 한함)를 하나의 문자열로 결합하여 반환합니다. 예를 들어 https://www.example.com:2544/aboutUs라는 URL이 있다면, origin 값은 https://www.example.com:2544가 됩니다.
문법(Syntax)
origin 속성의 값을 가져오는 기본 문법은 다음과 같습니다.
location.origin
예제(Example)
아래 예제를 통해 Location origin 속성이 실제로 어떻게 동작하는지 확인해 보겠습니다. 버튼을 클릭하면 현재 URL의 출처(origin) 정보가 화면에 표시됩니다.
<!DOCTYPE html>
<html>
<head>
<title>Location origin</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>Location-origin</legend>
<label for="urlSelect">현재 URL:</label>
<input type="url" size="30" id="urlSelect" value="https://www.example.com:2544/aboutUs">
<input type="button" onclick="getorigin()" value="출처(origin) 가져오기">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var urlSelect = document.getElementById("urlSelect");
function getorigin(){
divDisplay.textContent = 'URL Origin: '+location.origin;
}
</script>
</body>
</html>
실행 결과(Output)
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.
'출처(origin) 가져오기' 버튼을 클릭하기 전 −

'출처(origin) 가져오기' 버튼을 클릭한 후 −

버튼을 클릭하면 입력된 URL에서 프로토콜과 호스트, 포트 번호만 추출된 https://www.example.com:2544 값이 div 영역에 표시되는 것을 확인할 수 있습니다.
참고 사항
location.origin 속성은 Chrome, Firefox, Edge, Safari 등 대부분의 최신 브라우저에서 지원됩니다. 다만 구형 Internet Explorer에서는 지원되지 않으므로, 이 경우 location.protocol과 location.host 속성을 조합하여 동일한 결과를 얻을 수 있습니다.