TIL - Manifest V3

신혜린·2023년 12월 27일
0

TIL

목록 보기
15/19

구글 크롬 익스텐션 개발을 위해 다음 참고글을 회독하며 필기한 글입니다.


Manifest V3?

구글 크롬 익스텐션을 개발하기 위해서는 manifest.json 파일이 필수인데, 이 파일에는 package.json 처럼 익스텐션을 정의하는 정보가 포함되어 있다.

  • 참고로 2020년 11월 기준, Chrome은 개인정보보호, 보안 및 성능을 향상시킨 V3을 도입시켰으며 기존의 MV2는 단계적 폐지를 계획하고 있다.

Service Worker

service worker 는 웹 페이지가 아닌 브라우저가 백그라운드에서 실행하는 스크립트로, 웹 페이지와는 별개로 동작한다는 특징이 있다.
✅ 오프라인 액세스를 제공하여 안정성을 개선하고 페이지 성능을 높이는 것을 목표로 한다.
✅ 일정 시간이 되면 비활성화 상태가 되며, DOM을 직접 제어하는 게 불가능하므로 Message 기능을 이용하여 제어 대상 페이지와 통신한다.

💎 service worker 는 HTTP 캐시와는 완전히 별개인 캐싱 메커니즘인 Cache 인터페이스 이다.

  • Cache 인터페이스 : service worker 의 생명주기의 일부로, 캐시 된 ResponseRequest를 나타낸다.
    도메인은 여러개의 이름이 지정된 Cache 객체를 가질 수 있으며, 그 객체들은 service worker 가 완전히 제어한다. 따라서 service worker 스크립트가 Cache 업데이트를 어떻게 컨트롤 할지에 대해서 구현해야 한다.
  • 명시적으로 요청하지 않으면 Cache 항목들은 업데이트 되지 않는다.
  • Cache를 삭제하지 않으면 만료되지 않는다.

Service Worker와 통신하기 (feat. Message)

server workerMessage 를 통해 익스텐션과 통신한다.

  • service worker 는 익스텐션이 보낸 메시지를 수신하여 서비스 로직을 수행 한 뒤 Response 를 되돌려주는 역할을 한다. (하나의 작은 서버 역할)

work-flow 예시)

// popup.js
chrome.runtime.sendMessage({
  message: 'userStatus'
}, (respone) => {
  if (response.message === 'success') {
    console.log('로그인 성공');
  } else if (response.message === 'login'){
    console.log('로그인하세요.');
    window.location.href = './login.html';
  }
});
  • 익스텐션을 실행하면 popup.js 가 실행되어 userStatus 를 묻는 메시지를 service worker 에 전송한다. 이후에는 콜백 함수를 실행한다.
  • service workeruserStatus 메시지를 수신하여 로그인 확인을 한 뒤, popup.jsResponse 를 전달한다.
  • popup.jsResponse 에 담긴 각 메시지에 맞는 작업을 수행한다.
  • 로그인이 필요한 경우 service workerlogin 메시지를 응답값으로 보내어 login.htmlredirect 한다.

// background.js
function isLogedIn(sendResponse) {
  chrome.storage.local.get(['userStatus'], (response) => {
    const error = chrome.runtime.lastError;
    if (error) console.log(error);
    
    if (!response.userStatus) {
      sendResponse({ message: 'login' });
    } else {
      sendResponse({ message: 'success' });
    }
  });
};
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === 'userStatus') {
    isLogedIn(sendRespone);
    return true;
  }
});
  • service workeruserStatus 메시지를 수신하여 로그인을 확인하는 isLogedIn 함수를 실행한다.

    isLogedIn 함수는 익스텐션의 storage 에 저장된 값을 꺼내어 로그인 상태를 확인하는 역할을 한다. (chrome.storage.local.get)

    • storagebrowserlocal storage, session storage 와 별개로 익스텐션만이 가지고 있는 저장소이다. (개발자도구를 이용해 저장소를 직접 살펴보는 것은 불가능)
    • 그래도 유저 기밀 정보를 이 곳에 저장하지 않는 것이 좋음.
  • isLogedIn 함수의 매개변수는 sendResponse이며, 이는 popup.js 에 응답 메시지를 전달하는데 사용된다.

  • return true; 를 통해 response 를 받아야하는 곳에서 비동기로 콜백함수를 호출할 수 있게 된다.


// login.js
document.querySelector('form').addEventListener('submit', (e) => { 
  e.preventDefault();
  
  const email = document.querySelector('#email').value;
  const pwd = document.querySelector('#password').value;
  
  chrome.runtime.sendMessage({
    message: 'login',
    payload: { email, pwd }
  }, (response) => {
    if (response === 'success') {
      window.location.href = './popup.html';
    } else {
      alert('로그인 실패');
    }
  });
});
  • 아이디, 비밀번호를 payload에 담아 login 메시지를 service worker에 전달한다.
  • response 의 성공, 실패 여부에 따라 login.js 의 다음 동작을 작성할 수 있다.

// background.js
// ...
async funstion getAuth(userInfo, sendResponse) {
  const params = {
    email: userInfo.email,
    passwor: userInfo.pwd
  };
  const response = await fetch('yourUrl', {
    method: 'POST',
    body: JSON.stringify(params),
    headers: { 'Content-Type': 'application/json' }
  });
  if (response.status !== 200) {
    sendResponse('fail');
  } else {
    const result = await response.json();
    chrome.storage.local.set({
      userStatus: result.userStatus
    }, (res) => {
      if (chrome.runtime.lastError) sendResponse('fail');
      sendResponse('success');
    });
  }
};
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === 'userStatus') {
    isLogedIn(sendResponse);
    return true;
  } else if (request.message === 'login') {
    getAuth(request.payload, sendResponse);
    return true;
  }
});
  • login 메시지를 수신한 service worker 는 서버에 로그인 요청을 하는 getAuth 함수를 실행한다.
  • 로그인에 성공하게 되면 익스텐션의 storage 에 로그인 상태를 저장하고 success 메시지를 응답으로 보낸다.

work-flow 도식화

profile
개 발자국 🐾

0개의 댓글