보편적이지 않은 코딩

웹페이지에서 공부한 단어의 수를 세기 (크롬 확장 기능 만들기)

수업소개

웹페이지를 소비하는 입장에서도 웹페이지를 대상으로 여러가지 프로그래밍을 할 수 있는 방법이 많습니다. 최근의 웹브라우저들은 대부분 개발자 도구를 제공합니다. 이것을 이용하면 웹페이지의 소비자도 분석작업을 비롯한 여러가지 일을 할 수 있습니다. 여기서는 이것을 이용해 자신이 쓰기 위한 간단한 프로그램을 만드는 방법을 소개해드립니다. 이렇게 만들어진 개인적 프로그램을 구글 확장 프로그램으로 만들어서 누구나 사용할 수 있는 프로그램으로 승화시키는 방법도 함께 알아봅니다. 

수업의 효과

  • 개인적 코딩의 사례
  • 구글 크롬 확장 기능 만들기
  • 탈웹화 (웹이 아닌 분야에서 웹기술의 활용)

미리보기

수업

google developer console

//이 문서에서 body  태그 아래에 있는 모든 텍스를 가져온다. 그 결과를 bodyText라는 변수에 담는다.
var bodyText = document.querySelector('body').innerText;
//bodyText의 모든 단어를 추출하고, 그 단어의 숫자를 센다. 그 결과를 bodyNum이라는 변수에 담는다.
var bodyNum = bodyText.split(' ').length;
//bodyText에서 자신이 알고 있는 단어(the)가 몇번 등장하는지를 알아본다. 그 결과를 myNum이라는 변수에 담는다.
var myNum = bodyText.match(new RegExp('\\b(the|is|was|of)\\b', 'gi')).length;
myNum+'/'+bodyNum +'('+ (myNum/bodyNum*100)+'%)';

예제

manifest.json

{
  "manifest_version": 2,

  "name": "FrequencyOf",
  "description": "My lovely words",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ]
}

popup.html

<!doctype html>
<html>
  <head>
    
  </head>
  <body>
    <h1>FrequencyOf</h1>
  </body>
</html>

script.js

//컨텐츠 페이지를 대상으로 코드를 실행해주세요. 
chrome.tabs.executeScript({
  code:'var bodyText = document.querySelector("body").innerText;alert(bodyText);'
});

popup.html 

<!doctype html>
<html>
  <head>
    
    <style>
      body{
        width:400px;
        padding:1rem;
      }
      textarea{
        width:100%;
        font-size:2rem;
      }
      #result{
        font-size:2.5rem;
      }
    </style>
  </head>
  <body>
    <h1>FrequencyOf</h1>
    <textarea id="user" rows="3"></textarea>
    <div id="result"></div>
    <script src="script.js"></script>
  </body>
</html>

script.js 

//컨텐츠 페이지의 #user 입력된 값이 변경 되었을 '때'
document.querySelector('#user').addEventListener('change', function () {
  //컨텐츠 페이지에 몇개의 단어가 등장하는지 계산해주세요. 
  var user = document.querySelector('#user').value;

  //컨텐츠 페이지를 대상으로 코드를 실행해주세요. 
  chrome.tabs.executeScript({
    code: 'document.querySelector("body").innerText'
  }, function (result) {
    // 위의 코드가 실행된 후에 이 함수를 호출해주세요. 그 때 result에 담아주세요. 

    //이 문서에서 body  태그 아래에 있는 모든 텍스를 가져온다. 그 결과를 bodyText라는 변수에 담는다.
    var bodyText = result[0];
    //bodyText의 모든 단어를 추출하고, 그 단어의 숫자를 센다. 그 결과를 bodyNum이라는 변수에 담는다. 
    var bodyNum = bodyText.split(' ').length;
    //bodyText에서 자신이 알고 있는 단어(the)가 몇번 등장하는지를 알아본다. 그 결과를 myNum이라는 변수에 담는다.
    var myNum = bodyText.match(new RegExp('\\b(' + user + ')\\b', 'gi')).length;

    var per = myNum / bodyNum * 100;
    per = per.toFixed(1);
    // id값이 result인 태그에 결과를 추가한다. 
    document.querySelector('#result').innerText = myNum + '/' + bodyNum + '(' + (per) + '%)';


  });

});

manifest.json 

{
  "manifest_version": 2,

  "name": "FrequencyOf",
  "description": "My lovely words",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "storage"
  ]
}

script.js

function matching(user){
  chrome.tabs.executeScript({
    code: 'document.querySelector("body").innerText'
  }, function (result) {
    // 위의 코드가 실행된 후에 이 함수를 호출해주세요. 그 때 result에 담아주세요. 
    //이 문서에서 body  태그 아래에 있는 모든 텍스를 가져온다. 그 결과를 bodyText라는 변수에 담는다.
    var bodyText = result[0];
    //bodyText의 모든 단어를 추출하고, 그 단어의 숫자를 센다. 그 결과를 bodyNum이라는 변수에 담는다. 
    var bodyNum = bodyText.split(' ').length;
    //bodyText에서 자신이 알고 있는 단어(the)가 몇번 등장하는지를 알아본다. 그 결과를 myNum이라는 변수에 담는다.
    var myNum = bodyText.match(new RegExp('\\b(' + user + ')\\b', 'gi')).length;
    var per = myNum / bodyNum * 100;
    per = per.toFixed(1);
    // id값이 result인 태그에 결과를 추가한다. 
    document.querySelector('#result').innerText = myNum + '/' + bodyNum + '(' + (per) + '%)';
  });
}


//크롬 스토리지에 저장된 값을 가져오세요. 
chrome.storage.sync.get(function (data) {
  // #user의 값으로 data의 값을 입력해주세요. 
  document.querySelector('#user').value = data.userWords;

  //분석해서 그 결과를 #result에 넣어주세요. 
  matching(data.userWords);

});

//컨텐츠 페이지의 #user 입력된 값이 변경 되었을 '때'
document.querySelector('#user').addEventListener('change', function () {
  //컨텐츠 페이지에 몇개의 단어가 등장하는지 계산해주세요. 
  var user = document.querySelector('#user').value;

  // 크롬 스토리지에 입력값을 저장한다. 
  chrome.storage.sync.set({
    userWords: user
  });

  //컨텐츠 페이지를 대상으로 코드를 실행해주세요. 
  matching(user);

});

댓글

댓글 본문
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기