본문 바로가기
웹개발/크롬 익스텐션

크롬 익스텐션 개발기(2) : webclipper

by 현댕5697 2021. 1. 25.
반응형

우리 프로그램의 주된 기능은 webclipper 기능이었다.

즉, 익스텐션의 파비콘을 클릭했을 때 해당 탭의 html 정보를 긁어오는 과정이 필요하였다.

그래서 나는 이 기능을 구현하기 위해 나는 background 부분과 chrome API를 이용하였다.

developer.chrome.com/docs/extensions/reference/

 

API Reference - Chrome Developers

The complete reference to all APIs made available to Chrome Extensions. This includes APIs for the deprecated Chrome Apps platform as well as APIs still in beta and dev.

developer.chrome.com

 

가장 최선의 방법은 파비콘을 클릭하는 것을 인식하고, 현재 페이지의 html 정보를 불러오는 것이었다.

이러한 기능을 도와주는 chrome API를 찾아봤더니 chrome.browserAction.onClicked.addListener 라는 것이 있었다.

설명에

"Fired when a browser action icon is clicked."

라고 적혀있어서 뭔가 파비콘을 클릭하는 것을 인식할 수 있을 것 같았는데, 그 뒤의 문장에

"Does not fire if the browser action has a popup."

라고 적혀있어서 팝업기능을 사용하는 우리 프로그램에서는 쓸 수 없었다.

 

그래서 이 API를 사용하는 대신 다른 방법을 택하여야 했다.

 

우리 프로그램에서는 파비콘을 클릭하면 Loading component가 실행되도록 하였는데,

이때 Loading component안에 chrome.runtime.sendMessage API 를 사용하여 파비콘이 클릭되었다는 정보를 background 부분으로 전달하였다.

chrome.runtime.sendMessage({ IsFaviconClick: true });

 

background의 index.js 파일에서는 chrome.runtime.onMessage.addListene 를 통해 message를 수신하였다.

수신한 message로 부터 파비콘이 클릭되었는지에 대한 정보를 얻을 수 있다.

그 후 chrome.tabs.query 를 통해 현재 페이지의 url을 가져올 수 있다.

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if(message.isFaviconClick){
    chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => {
      const url = tabs[0].url;
      const HTML = returnHTML(url);
      HTML.then(function (html) {
        findOgTag(html, 'image', data);
      }
    }
  }
});

const returnHTML = async url => {
  let HTML = await getHTML(url);
  return HTML.data;
};

const getHTML = async url => {
  try {
    return await axios.get(url);
  } catch (error) {
    console.log(error);
  }
};

 

findOgTag() 함수는 가져온 html 데이터에서 og태그와 관련된 데이터를 추출하기 위해 만든 함수이다.

 

og태그는 특정 사이트의 썸네일, 사이트 이름, 사이트 제목과 같은 정보와 관련이 있다.

사실 정확히 말하면 meta태그 안에 property가 og로 되어있는 형식이다.

<meta property="og:url" content="https://carpediem9911.tistory.com/" >
<meta property="og:site_name" content="tistory" >
<meta property="og:title" content="carpe diem" >

 

그래서 나는 사이트의 핵심 정보를 쉽게 추출하기 위해 og태그를 사용하였다.

 

보통 웹크롤링을 하는 방법을 찾아보니 jquery를 많이 사용하던데, 내가 사용한 boiler plate에서 jquery를 어떤식으로 넣어야 할지 알 수 없었다.

그래서 그냥 문자열을 검색해서 원하는 데이터를 찾는 방식으로 함수를 짰다.

내가 현재 짠 코드보다 더 좋은 방법이 있을 것 같아서 이 부분은 한번 더 생각해봐야겠다!!

 

jquery를 전혀 사용하지 않아도 됐었다!!!

리액트에서 cheerio 라이브러리를 사용하면 훨씬 간편하게 태그를 추출할 수 있었다.

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if(message.isFaviconClick){
    chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => {
      const url = tabs[0].url;
      const HTML = returnHTML(url);
      HTML.then(function (html) {
        const $ = cheerio.load(html);
	    data.title = $("meta[property='og:title']").attr("content");
	    data.content = $("meta[property='og:description']").attr("content");
	    data.thumbnail = $("meta[property='og:image']").attr("content");
      }
    }
  }
});

const returnHTML = async url => {
  let HTML = await getHTML(url);
  return HTML.data;
};

const getHTML = async url => {
  try {
    return await axios.get(url);
  } catch (error) {
    console.log(error);
  }
};

 

 

 

 

반응형

댓글