DEV Community

panfan
panfan

Posted on • Originally published at manon.icu on

Chrome插件开发 - Creating the TurboReader browser extension

本章学习如何创建turboReader插件,如下图:

<video
src={
'https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/turboreader_ghlbnk.webm'
}
autoPlay

初始化项目

mkdir turboReader && cd turboReader
Enter fullscreen mode Exit fullscreen mode

添加manifest.json.json

{
  "manifest_version": 3,
  "version": "1.0",
  "name": "TurboReader",
  "description": "Become a faster reader with TurboReader",
  "action": {},
  "icons": {
    "48": "icons/icon-48.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["activeTab", "scripting"]
}
Enter fullscreen mode Exit fullscreen mode

添加background.js,获取活动标签,并注入名为turboMode的函数。

const turboMode = () => {
  // do something
}

chrome.action.onClicked.addListener(async () => {
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true})
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    function: turboMode
  })
})
Enter fullscreen mode Exit fullscreen mode

创建函数

首先获取页面内所有段落

const paragraphs = document.getElementsByTagName('p')
Enter fullscreen mode Exit fullscreen mode

判断当前是否是阅读模式

const isTurboMode = document.body.classList.contains('trms')
Enter fullscreen mode Exit fullscreen mode

遍历并处理段落

for (const paragraph of paragraphs) {
  if (isTurboMode) {
    // 阅读模式已开启就返回当前段落
    paragraph.innerText = paragraph.innerText
  } else {
    // 阅读模式未开启,返回处理后的段落
    paragraph.innerHTML = paragraph.innerText
      .split(' ')
      .map((word) => {
        const length = word.replace(/[^a-zA-Z0-9]+$/, '').length
        const boldLength = length === 1 ? 1 : Math.floor(length / 2)
        return `<strong>${word.substring(
          0,
          boldLength
        )}</strong>${word.substring(boldLength)}`
      })
      .join(' ')
  }
}
Enter fullscreen mode Exit fullscreen mode

在循环外部加入判断

isTurboMode
  ? document.body.classList.remove('trms')
  : document.body.classList.add('trms')
Enter fullscreen mode Exit fullscreen mode

完整代码

const turboMode = () => {
  const paragraphs = document.getElementsByTagName('p')
  const isTurboMode = document.body.classList.contains('trms')
  for (const paragraph of paragraphs) {
    if (isTurboMode) {
      paragraph.innerText = paragraph.innerText
    } else {
      paragraph.innerHTML = paragraph.innerText
        .split(' ')
        .map((word) => {
          const length = word.replace(/[^a-zA-Z0-9]+$/, '').length
          const boldLength = length === 1 ? 1 : Math.floor(length / 2)
          return `<strong>${word.substring(
            0,
            boldLength
          )}</strong>${word.substring(boldLength)}`
        })
        .join(' ')
    }
  }

  isTurboMode
    ? document.body.classList.remove('trms')
    : document.body.classList.add('trms')
}
Enter fullscreen mode Exit fullscreen mode

Source Code

【Source Code】

Top comments (0)