JavaScript / window.open / 새 창 띄우기, 부모 창과 자식 창 사이 값 전달하기

window.open으로 새 창을 띄우고, 부모 창에서 자식 창으로, 자식 창에서 부모 창으로 값을 전달하는 방법을 정리한다.

부모 창이 parent.html, 자식 창이 child.html이다.

새 창 띄우기

문법은 다음과 같다.

window.open( url, windowName, windowFeatures );
  • url : 새 창에 들어갈 문서 주소
  • windowName : 윈도우 이름
  • windowFeatures : 새 창의 특성

예를 들어 다음은...

window.open( "child.html", "Child", "width=400, height=300, top=50, left=50" );

child.html을 새 창으로 띄우고, 윈도우 이름은 Child, 가로 크기는 400px, 세로 크기는 300px, 위치는 화면의 위에서 50px, 왼쪽에서 50px라는 뜻이다.

새 창의 크기는 콘텐츠 영역으로, 창의 테두리, 주소 표시줄 등은 포함되지 않는다.

parent.html

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Parent</title>
    <style>
      * {
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Parent</h1>
    <p><input type="button" value="New Window" onclick="new_window();"></p>
    <script>
      function new_window() {
        window.open(
          "child.html",
          "Child",
          "width=400, height=300, top=50, left=50"
        );
      }
    </script>
  </body>
</html>

child.html

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Child</title>
    <style>
      * {
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Child</h1>
  </body>
</html>

화면의 가운데에 새 창 띄우기

parent.html

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Parent</title>
    <style>
      * {
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Parent</h1>
    <p><input type="button" value="New Window" onclick="new_window();"></p>
    <script>
      var new_window_width = 400;
      var new_window_height = 300;
      var positionX = ( window.screen.width / 2 ) - ( new_window_width / 2 );
      var positionY = ( window.screen.height / 2 ) - ( new_window_height / 2 );
      function new_window() {
        window.open(
          "child.html",
          "Child",
          "width=" + new_window_width + ", height=" + new_window_height + ", top=" + positionY + ", left=" + positionX
        );
      }
    </script>
  </body>
</html>

자식 창에서 부모 창으로 값 보내기

우편번호 조회하여 주소 입력하는 것처럼, 부모 창에서는 입력하지 못하고, 자식 창에서 조회 또는 입력한 값만 부모 창에서 사용하고 싶을 때 유용하다.

parent.html

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Parent</title>
    <style>
      * {
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Parent</h1>
    <p>
      <input type="text" id="parentValue" readonly>
      <input type="button" value="New Window" onclick="new_window();">
    </p>
    <script>
      function new_window() {
        window.open(
          "child.html",
          "Child",
          "width=400, height=300, top=50, left=50"
        );
      }
    </script>
  </body>
</html>

child.html

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Child</title>
    <style>
      * {
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Child</h1>
    <p>
      <input type="text" id="childValue">
      <input type="button" value="Send Value" onclick="sendValue();">
    </p>
    <script>
      function sendValue() {
        window.opener.document.getElementById( "parentValue" ).value = document.getElementById( "childValue" ).value;
        window.close();
      }
    </script>
  </body>
</html>

자식 창에서 부모 창 값 가져오기

아이디 중복 검사하는 것처럼, 부모 창에서 입력한 값을 자식 창에서 검색 또는 검증할 때 유용하다.

parent.html

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Parent</title>
    <style>
      * {
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Parent</h1>
    <p>
      <input type="text" id="parentValue">
      <input type="button" value="Send Value" onclick="new_window();">
    </p>
    <script>
      function new_window() {
        window.open(
          "child.html",
          "Child",
          "width=400, height=300, top=50, left=50"
        );
      }
    </script>
  </body>
</html>

child.html

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Child</title>
    <style>
      * {
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>Child</h1>
    <p>
      <input type="text" id="childValue">
    </p>
    <script>
      document.getElementById( "childValue" ).value = window.opener.document.getElementById( "parentValue" ).value;
    </script>
  </body>
</html>

Related Posts

JavaScript / Object / document.getElementById()

JavaScript / Object / document.getElementById()

.getElementById() .getElementById()는 id의 값으로 특정한 값을 가진 요소를 가져옵니다. 문법 document.getElementById( 'id' ) id에는 가져오려는 요소의 id의 값을 넣습니다. 예를 들어 var jb = document.getElementById( 'xyz' ); 는 id의 값이 xyz인 요소를 가져와서 변수 jb에 저장합니다. 예제 id의 값이 ab인 요소를 가져와서 몇 가지를 출력하는 예제입니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> ...

JavaScript / Object / Array.every() / 모든 원소가 조건에 맞는지 검사하는 메서드

JavaScript / Object / Array.every() / 모든 원소가 조건에 맞는지 검사하는 메서드

.every() .every()는 배열의 모든 원소가 조건에 맞는지 검사하는 메서드입니다. 모든 원소가 조건을 만족하면 true, 하나라도 만족하지 않으면 false를 반환합니다. 예제 배열의 원소를 오름차순으로 검사하고, 조건을 만족하지 않는 원소가 있으면 검사를 중지하고 false를 반환합니다. 모든 원소를 다 검사했는데 조건을 만족하지 않는 원소가 없으면 true를 반환합니다. 원소가 없는 빈 배열은, 조건은 만족하지 않는 원소가 없으므로 무조건 ...

JavaScript / Object / Location / URL 정보 가져오는 객체

JavaScript / Object / Location / URL 정보 가져오는 객체

location location은 URL 정보를 가져오는 객체입니다. URL 전체 또는 일부의 정보를 가져올 수 있는데, 대표적인 것들은 다음과 같습니다. location location.host location.hostname location.href location.pathname location.protocol 예제 URL이 https://example.codingfactory.net/script/script.html 일 때, 각 객체 속성이 어떤 값을 가져오는지 알아보는 예제입니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> h1 { ...

JavaScript / Object / String.repeat() / 문자열을 반복한 값을 반환하는 메서드

JavaScript / Object / String.repeat() / 문자열을 반복한 값을 반환하는 메서드

.repeat() .repeat() – 문자열을 반복한 값을 반환하는 메서드입니다. IE는 Edge부터 지원합니다. 문법 string.repeat( count ) 예제 'abc'.repeat( 2 ) abc를 두 번 반복한 abcabc를 반환합니다.

JavaScript / Object / Element.removeAttribute() / 요소의 속성을 제거하는 메서드

JavaScript / Object / Element.removeAttribute() / 요소의 속성을 제거하는 메서드

.removeAttribute() .removeAttribute()는 요소의 속성을 제거하는 메서드입니다. 문법 element.removeAttribute( attributename ) 예를 들어 document.getElementsByTagName( 'h1' ).removeAttribute( 'class' ); 는 문서의 첫번째 h1 요소의 class 속성을 제거합니다. 예제 첫번째 h1 요소의 class 속성을 제거해서 글자색이 검정색이 됩니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } .abc { color: red; } </style> </head> <body> <h1 class="abc">Lorem ...

JavaScript / Object / String.substring() / 문자열 추출하는 메서드

JavaScript / Object / String.substring() / 문자열 추출하는 메서드

.substring() .substring()은 문자열에서 특정 부분만 골라낼 때 사용하는 메서드입니다. 문법 string.substring( start, end ) start와 end로 문자열에서 골라낼 부분의 처음과 끝을 지정합니다. 예를 들어 var str = '123456789'; document.write( str.substring( 1, 4 ) ); 는 234를 출력합니다. start 값은 필수이며, end 값이 지정되지 않으면 문자열의 끝까지를 의미합니다. 예제 1 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> ...

JavaScript / Object / Array.indexOf(), Array.lastIndexOf() - 일치하는 요소의 위치(인덱스)를 반환하는 메서드

JavaScript / Object / Array.indexOf(), Array.lastIndexOf() - 일치하는 요소의 위치(인덱스)를 반환하는 메서드

.indexOf() .indexOf()는 주어진 값과 일치하는 요소의 인덱스를 반환하는 메서드입니다. 문법 array.indexOf( value, start ) value : 찾으려는 값을 넣습니다. start : 검색을 시작할 인덱스 값입니다. 생략 가능하고, 생략했을 경우 값은 0입니다. 일치하는 원소가 있다면 인덱스를 반환합니다. 여러 개 있으면 처음 원소의 인덱스를 반환합니다. 없다면 -1을 반환합니다. 예제 배열 원소의 인덱스는 0부터 시작합니다. 즉, 첫번째 원소의 인덱스는 0, 두번째 ...

JavaScript / Object / Screen / 화면 정보 가져오는 객체

JavaScript / Object / Screen / 화면 정보 가져오는 객체

Screen Screen은 화면 정보를 가져오는 객체입니다. 속성은 다음과 같습니다. screen.width 화면의 가로 크기를 가져옵니다. screen.height 화면의 세로 크기를 가져옵니다. screen.availWidth 작업 표시줄이 차지하는 부분을 제외한 가로 크기를 가져옵니다. screen.availHeight 작업 표시줄이 차지하는 부분을 제외한 세로 크기를 가져옵니다. screen.colorDepth screen.pixelDepth IE는 버전 10 이상에서 사용할 수 있습니다. 예제 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } </style> ...

JavaScript / 연산자 / typeof

JavaScript / 연산자 / typeof

typeof 연산자 typeof는 변수의 데이터 타입을 반환하는 연산자입니다. 문법 typeof variable variable에는 데이터 또는 변수가 들어갑니다. 괄호를 사용해도 됩니다. typeof(variable) 반환되는 값은 다음과 같습니다. undefined : 변수가 정의되지 않거나 값이 없을 때 number : 데이터 타입이 수일 때 string : 데이터 타입이 문자열일 때 boolean : 데이터 타입이 불리언일 때 object : 데이터 타입이 함수, 배열 등 객체일 때 function : 변수의 ...

JavaScript / Object / Array.push(), Array.pop(), Array.unshift(), Array.shift() - 배열에 원소 추가/제거 하기

JavaScript / Object / Array.push(), Array.pop(), Array.unshift(), Array.shift() - 배열에 원소 추가/제거 하기

.push(), .pop(), unshift(), shift() .push()는 배열의 맨 끝에, .unshift()는 배열의 맨 앞에 원소를 추가합니다. .pop()은 마지막 원소를, .shift()는 맨 앞의 원소를 제거합니다. 예제 네 가지 속성을 비교하는 간단한 예제입니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <script> ...