TIL - Chrome Extensions 튜토리얼 (2)

신혜린·2023년 12월 31일
0

TIL

목록 보기
17/19
post-thumbnail

Chrome Extension 튜토리얼 따라하기 (2)
참고 | Reading Time


파일 구조

ㄴ my-extension/
	├ manifest.json 💡 루트 디렉토리에 위치
    ├ src/
    ⎮	ㄴ content.js
    ⎣ public/
    	⎣ images/
    		├ icon-16.png
            ├ icon-32.png
            ├ icon-48.png
        	ㄴ icon-128.png

Manifest.json

{
  "manifest_version": 3,
  "name": "Reading time",
  "version": "1.0",
  "description": "Add the reading time to Chrome Extension documentation articles",
    
  "content_scripts": [
    {
      "js": ["src/content.js"],
      "matches": [
        "https://developer.chrome.com/docs/extensions/*",
        "https://developer.chrome.com/docs/webstore/*"
      ]
    }
  ],
    
  "icons": {
    "16": "images/icon-16.png",
    "32": "images/icon-32.png",
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  }
}

💡 contenst_scripts > matches

: 패턴 매칭 으로, 특정 패턴에 맞는 데이터를 찾거나 추출하는 기능을 한다.

<scheme>://<host>/<path> 의 구조를 띈다.

  • <scheme> : 이중 슬래시(//)를 사용하여 나머지 패턴과 구분하는 것
    • http
    • https
    • http 또는 https만 일치하는 와일드 카드 *
    • file
  • <host> : 호스트 이름을 나타낸다. (예. www.example.com)
    • 호스트 패턴에 와일드 카드 (*)를 사용하는 경우 첫 번째 문자로 오는 유일한 문자여야 하고 그 뒤에 마침표(.) 또는 슬래시(/)가 와야 한다. (예. *.example.com)
  • <path> : 슬래시(/)를 포함해야 한다. 슬래시만 사용할 경우 모든 경로와 일치한다.

💡 icons

아이콘들이 사이즈 별 로 존재하는 이유?

16x16 : 확장 프로그램 페이지 및 컨텍스트 메뉴의 favicon
32x32 : Windows 컴퓨터용
48x48 : 광고 확장 페이지 표시용
128x128 : 설치 시 및 Chrome 웹 스토어 표시용

contents.js

const article = document.querySelector("article");

if (article) {
  const text = article.textContent;
  const wordMatchRegExp = /[^\s]+/g; // Regular expression
  const words = text.matchAll(wordMatchRegExp);
  const wordCount = [...words].length;
  const readingTime = Math.round(wordCount / 200);
  const badge = document.createElement("p");

  badge.classList.add("color-secondary-text", "type--caption");
  badge.textContent = `⏱️ ${readingTime} min read`;

  // Support for API reference docs
  const heading = article.querySelector("h1");
  // Support for article docs with date
  const date = article.querySelector("time")?.parentNode;

  (date ?? heading).insertAdjacentElement("afterend", badge);
}

해당 익스텐션을 업로드 하고 패턴 매칭과 일치하는 페이지 오픈 시 ⏱️ ${readingTime} min read 가 표시되는 것을 확인할 수 있다.

profile
개 발자국 🐾

0개의 댓글