자바스크립트 끄적끄적

html 에서 html 로 데이터 보내기 with 바닐라 자바스크립트

코딩질문자 2023. 12. 8. 15:24
728x90

# 리액트나 뷰 이런 프레임워크에서는 props로 데이터를 간단하게 보낸다. 그런데 문득 그러한 프레임워크를 쓰지 않고, 어떤 식으로 데이터를 보낼지가 궁금하다. 또한 가끔 일을 하다 보면 그러한 코드를 마주할 때가 있다. 그런 상황에서 좀 더 쉽게 어려움을 해결하고자 이 글을 정리한다.

 

## 들어가기에 앞서

 

우선 로컬스토리지, 세션, 쿠키로 저장해서 가져다 쓰는 방법은 언급하지 않겠다. 또한 서버가 있다고 가정하고 서버에 데이터를 보내고 받아오는 형식도 고려하지 않겠다. 단순히 두 html 간에 데이터를 간단하게 전송하고자할 때의 상황을 고려하겠다.

 


 

#### 보내는 페이지: pageA.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Page A</title>
</head><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Page A</title>
</head>
<body>

<button id="sendButton">Send Message from Page A</button>

<script>
  // 보낼 데이터
  const data = 'To pageB.html. sending the Data from A';

  const sendDataToB = document.querySelector('#sendButton');
  sendDataToB.addEventListener('click', () => {
    // 데이터를 encodeURIComponent 함수를 사용하여 인코딩
    const encodedData = encodeURIComponent(data);
    // loaction.href = callBackUrl + '?param1=1&param2=2'
    location.href = `pageB.html?param1=${encodedData}`;
  });
</script>

</body>
</html>

 

##### 설명

 

간단한 코드이다. sendButton을 id로 가진 데이터를 보내면 data로 정의된 값을 보낸다. 그리고 그 값의 키는 param1로 보내는 것. 무엇을 이용해서? location.href를 이용해서

 

- location.href 란?


   href 는 location 객체에 속해있는 프로퍼티로 현재 접속중인 페이지 정보를 갖고 있습니다.
   또한 값을 변경할 수 있는 프로퍼티이기 때문에 다른 페이지로 이동하는데도 사용되고 있습니다.

 - 자바스크립트 location.href 로 현재페이지 확인 방법


   location.href;

 - 자바스크립트 location.href 로 페이지 이동 방법

 


 

#### 받는 페이지: pageB.html

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Page B</title>
</head>
<body>

<h1>Page B</h1>
<p id="receivedData"></p>

<script>
  // 현재 URL에서 쿼리 매개변수를 가져옴
  const urlParams = new URLSearchParams(window.location.search);

  // 쿼리 매개변수 중 'data' 값을 가져옴
  const encodedData = urlParams.get('param1');

  // 디코딩된 값을 출력
  const decodedData = decodeURIComponent(encodedData);

  // 받은 데이터를 페이지에 표시
  const receivedDataElement = document.getElementById('receivedData');
  receivedDataElement.textContent = `Received Data in Page B: ${decodedData}`;
</script>

</body>
</html>

 

##### 설명

 

window.location.search

'?' 뒤의 쿼리스트링을 가져옵니다.

const urlParams = new URLSearchParams(window.location.search);  // 쿼리 스트링을 가져온다.
const encodedData = urlParams.get('param1'); // key값 param1 기준으로 데이터를 가져온다.
그다음 데이터를 쓰는 동작.
 

 

#### 동작 모습

 
pageA.html
 
 

 

pageB.html

 후기

 

찾아보면서 여러 방법으로 데이터를 보낼 수 있지만 간단하게 보낼 때 이 방법이 제일 깔끔한거 같다. 이정도만 알고 가도 바닐라자바스크립트로 구현할일 생기고, 데이터를 전송하려고 할 때 어려움이 다소 덜하지 않을까 생각한다.
 
 

 

##### 추가: window.location 관련 매서드

 

window.location.href

전체 URL 문자열을 가져옵니다.

 

window.location.protocol

마지막 ':'를 포함한 프로토콜 정보를 가져옵니다.

 

window.location.host

URL의 호스트 정보를 가져옵니다. 

위 예제는 포트번호가 없지만, 만약 URL에 포트번호가 있으면 ':'과 포트번호를 포함합니다.

 

window.location.hostname

URL의 호스트명을 가져옵니다.

이 값은 ':'과 포트번호를 포함하지 않습니다.

위 예제는 URL에 포트번호를 포함하지 않기 때문에 window.location.host와 window.location.hostname이 같습니다.

 
728x90