Content Script 설명 - Veloighter 제작기

holdOn·2021년 6월 8일
0
post-thumbnail

Content Script란?

  • 콘텐츠 스크립트는 웹페이지에서 작동하는 파일입니다. 이 콘텐츠 스크립트는 DOM을 사용하여 브라우저가 방문한 페이지를 바꿀 수 있습니다.

팔로우한 사용자의 Card UI가 High Lighting된 화면

팔로우한 사용자의 Card UI를 High Lighting하는 과정 요약

  1. 웹 페이지에 로드 되어있는 사용자의 이름들을 실시간으로 가져온다.
  2. 스토리지에 저장 되어있는 사용자의 이름과 비교한다.
  3. 실시간으로 가져온 사용자의 이름과 스토리지에 저장되어 있는 이름이 동일하고, 해당 Card UI가 테두리 처리가 되어있지 않다면 CSS로 테두리를 추가해준다.

실시간으로 사용자 이름 가져오기

const userInfos = document.getElementsByClassName('userinfo');
  • querySelectorAll을 사용할 경우 처음에 웹 피이지가 로드 되었을때의 NodeList를 가져옵니다. 그렇기 때문에 실시간으로 userinfo라는 class를 가진 a태그에서 사용자의 이름을 가져오기 위해 getElementByClassName을 사용 하였습니다.

High Lighting하는 코드

setInterval(function callBack() {
  BrowserStorage.getStorage().then((storage) => {
    storage.sync();

    /* eslint-disable @typescript-eslint/no-explicit-any */
    function highLightBorder(userNamesToHighlight: any): void {
      for (let index = 0; index < userNamesToHighlight.length; index += 1) {
        const userName = userNamesToHighlight[index].children[1].textContent
          .replace('by', '')
          .trim();
        const styledDiv =
          userNamesToHighlight[index].parentElement.parentElement;
        const span = userNamesToHighlight[index].children[1];
        const followers = storage.list();

        for (const follower of followers) {
          if (follower.userName === userName && span.className === '') {
            span.className = 'following';
            styledDiv.style.cssText = 'border: 3px solid rgb(18, 184, 134);';
          }
        }
      }
    }

    highLightBorder(userInfos);
    
    // High Lighthing 제거하는 코드
  });
}, 1000);

코드 설명

  • 웹 페이지가 계속 로드 되었을 때를 고려하여, High Lighting하는 기능을 반복하기 위해 setInterval메서드를 사용하였습니다.
  • 실시간으로 가져온 userinfo 클래스를 가진 a 태그의 텍스트 정보중에 사용자 이름만 가져옵니다.
  • userinfo 클래스를 가진 a 태그의 상위 div 태그와 하위의 span 태그의 DOM을 가져옵니다.
  • 스토리지에 저장 되어있는 사용자의 이름과 비교합니다.
  • 만약에 사용자의 이름이 동일하고, 하위 span 태그의 클래스가 없다면 'following'이라는 클래스를 추가해줍니다. 이것은 High Lighting 되어있는 카드에 또 다시 High Lighting하는 것은 방지하기 위해서입니다.

팔로우 리스트에서 삭제할 사용자의 Card UI의 High Lighthing 제거하는 과정 요약

  1. 배열의 includes 메서드를 사용하기 위해, 스토리지에서 팔로우한 사용자의 이름만 가지고 따로 새로운 배열을 만들어낸다.
  2. 그 배열에서 팔로우한 사용자의 이름이 존재하지 않고, userinfo 클래스를 가진 a 태그의 하위 span 태그 클래스에 'following'이 있는 DOM을 찾습니다.
  3. span DOM의 클래스를 초기화 시킵니다. High Lighting된 div DOM의 border는 CSS로 제거합니다.

High Lighting 제거하는 코드

setInterval(function callBack() {
  BrowserStorage.getStorage().then((storage) => {
    storage.sync();
	
    // High Lighthing하는 코드
    
    function getUserNames(): string[] {
      const followers = storage.list();
      const userNamesArray = [];

      for (const follower of followers) {
        userNamesArray.push(follower.userName);
      }

      return userNamesArray;
    }

    /* eslint-disable @typescript-eslint/no-explicit-any */
    function deleteBorder(userNamesToDelete: any): void {
      const userNamesArray = getUserNames();

      for (let index = 0; index < userNamesToDelete.length; index += 1) {
        const userName = userNamesToDelete[index].children[1].textContent
          .replace('by', '')
          .trim();
        const styledDiv = userNamesToDelete[index].parentElement.parentElement;
        const span = userNamesToDelete[index].children[1];

        if (
          !userNamesArray.includes(userName) &&
          span.className === 'following'
        ) {
          span.className = '';
          styledDiv.style.cssText = 'border: none;';
        }
      }
    }
    
    deleteBorder(userInfos);
  });
}, 1000);

코드 설명

  • getUserNames 기능에서 팔로우한 사용자의 이름만 가지고 만든 배열을 반환 받습니다.
  • 웹 페이지에 로드 되어있는 사용자의 이름과 비교합니다.(High Lighthing하는 과정과 동일합니다)
  • 반환 받은 배열에서 사용자의 이름이 존재하지 않고, span 태그의 클래스 이름이 'following'인 DOM을 찾아내어서 High Lighthing 되어있는 부분을 제거합니다.

Github 링크

profile
즐거운 마음으로 코딩하기 :)

0개의 댓글