퍼펫티어에서 마우스 위치 시각화

taelee·2020년 9월 19일
0
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({headless: false}); // default is true
  const page = await browser.newPage();
  await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
  await page.waitFor(3330);
  await page.evaluate(() => {
    (() => {
      const box = document.createElement('div');
      box.classList.add('mouse-helper');
      const styleElement = document.createElement('style');
      styleElement.innerHTML = `
          .mouse-helper {
            pointer-events: none;
            position: absolute;
            z-index: 100000;
            top: 0;
            left: 0;
            width: 20px;
            height: 20px;
            background: rgba(0,0,0,.4);
            border: 1px solid white;
            border-radius: 10px;
            margin-left: -10px;
            margin-top: -10px;
            transition: background .2s, border-radius .2s, border-color .2s;
          }
          .mouse-helper.button-1 {
            transition: none;
            background: rgba(0,0,0,0.9);
          }
          .mouse-helper.button-2 {
            transition: none;
            border-color: rgba(0,0,255,0.9);
          }
          .mouse-helper.button-3 {
            transition: none;
            border-radius: 4px;
          }
          .mouse-helper.button-4 {
            transition: none;
            border-color: rgba(255,0,0,0.9);
          }
          .mouse-helper.button-5 {
            transition: none;
            border-color: rgba(0,255,0,0.9);
          }
          `;
      document.head.appendChild(styleElement);
      document.body.appendChild(box);
      document.addEventListener('mousemove', event => {
        box.style.left = event.pageX + 'px';
        box.style.top = event.pageY + 'px';
        updateButtons(event.buttons);
      }, true);
      document.addEventListener('mousedown', event => {
        updateButtons(event.buttons);
        box.classList.add('button-' + event.which);
      }, true);
      document.addEventListener('mouseup', event => {
        updateButtons(event.buttons);
        box.classList.remove('button-' + event.which);
      }, true);
      function updateButtons(buttons) {
        for (let i = 0; i < 5; i++)
          box.classList.toggle('button-' + i, !!(buttons & (1 << i)));
      }
    })();
  });
  await page.mouse.move(200, 500);
  await page.waitFor(3000);
  await page.mouse.move(300, 500);
  await page.waitFor(3000);
  await page.mouse.move(400, 200);
  await page.waitFor(3000);
  await browser.close();
})();

위에 예시코드에서 evaluate부분을 넣어주면 그 뒤에 마우스 관련 행동들이 시각화돼서 보여진다.
위 코드는 npm i puppeteer -> node 코드를_저장한_파일명으로 실행 시킬수있다.

출처: https://github.com/ZeroCho/nodejs-crawler/blob/master/8.facebook-login-logout/index.js

profile
back-end, cloud, docker, web의 관심이 있는 예비개발자입니다.

0개의 댓글