Nuggets one-click three-link Google plug-in development and sharing

Get into the habit of writing together! This is the first day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

foreword

Google plug-in is a plug-in developed using front-end technologies such as html, js, and css to enhance browser functions. The plug-ins that programmers may use on a daily basis include HackBar, Vue.js devtools. With the help of Google plugins, we can easily make our own "customized" web pages and "customized" browsers.

During the Qingming holiday and the epidemic situation at home, I spent a day at home and developed a Google plug-in for Nuggets based on vue3.x+ts, which can realize one-click likes, collections and follow authors of Nuggets articles. The source address of the plugin is here~

Through this article, you can learn how to use vue3.x+ts to develop Google plug-in pages (in fact, it is the same as ordinary business development), and learn some small knowledge of Google plug-in development.

Start

Let's first look at the interaction effect:

a.gif

Sort out the following interactive function points:

  1. Click the plug-in icon to control the collapse or expansion of the sidebar;
  2. The switch button in the sidebar is used to control whether the plugin is enabled;
  3. Users can choose to trigger the three behaviors of like, favorite, and follow according to their own preferences (the default is one-click three times, and the like cannot be canceled);
  4. When the plug-in is enabled, enter the Nuggets article and like it, you can achieve the effect of one-click three-link.
  5. The data state of the plug-in is saved, and the page is refreshed without losing it

After the function is clear, we can start designing~

The Google plugin requires that there must be one in the directory manifest.json. We can configure one in it background.jsto monitor the user's click on the plugin icon, monitor the user's new tab, etc., and background.jsit will always run in the background.

Then we configure another one content.js, which content.jscan share the DOM with the web page and operate the DOM, but does not share the js of the web page. We can realize sidebar development by injecting iframe into the page, and inject js to realize the js logic that triggers one-click three-connection.

image.png

start

After sorting out the function points and designing the scheme, you can start coding. The structure of the project is as follows:

image.png

The content of the sidebar is a form. Although it is very simple, I used the mainstream technology stack of vue3.x++ vite2.x( NaiveUIa small test~).

I will pass the value change of the watch form, and then communicate the value change message to other parts

The main logic of the sidebar is as follows:

export const useAppOn = () => {
  const isAppOn = ref(false)

  watch(isAppOn, newVal => {
    const params = {
      from: iframePart,
      to: backgroundPart,
      key: appOnKey,
      value: newVal
    }
    chrome.runtime?.sendMessage(chrome.runtime.id, params)

    window.parent?.postMessage({
      from: iframePart,
      to: injectPart,
      key: appOnKey,
      value: newVal,
    }, '*')

    chrome.storage?.local.set({ [appOnKey]: newVal })
  })

  chrome.storage?.local.get([appOnKey], res => {
    if (res[appOnKey]) {
      isAppOn.value = !!res[appOnKey]
    }
  })

  return {
    isAppOn,
  }
}
复制代码

background.jsThe monitoring logic is as follows:

chrome.runtime.onMessage.addListener(({ from, to, key, value }) => {
  if (from === iframePart && to === backgroundPart && key === appOnKey) {
    if (value === true) {
      // balabala
    } else {
      // yy
    }
  }
})
复制代码

inject-page.jsThe monitoring logic is as follows:

window.addEventListener('message', ({ data: { from, to, key, value, initData } }) => {
    if (from === contentPart && to === injectPart && initData) {

      // 初始化数据
    } else if (from === iframePart && to === injectPart && key === appOnKey) {

      // 启动或停止插件
    } else if (from === iframePart && to === injectPart && key === checkItemsKey) {
      // ......
    }
  }, false)
复制代码

The conclusion is that the data communication of each part is achieved through chrome.runtime.sendMessageor through window.parent.postMessage,

After the injected js can get the data, it can simulate the behavior of one key and three connections according to the form data.

const $agreeBtn = document.querySelector('.article-suspended-panel .panel-btn')
  $agreeBtn?.addEventListener('click', () => {
    if ($agreeBtn.className.includes('active') || !pageConfig.isAppOn) {
      // 取消点赞行为就不往下走
      // 未开启插件就不往下走
      return
    }

    if (pageConfig.formData.follow) {
      follow()
    }
    // ......
  })
  
  function follow() {
    const $followBtn = document.querySelector<HTMLElement>('.article-area .follow-button')
    if (!$followBtn.className.includes('followed')) {
      $followBtn.click()
    }
  }
复制代码

After the code is written, when packaging, you need to compile ts into js and manifest.jsoncopy the icons to the dist directory

import { exec } from 'child_process'

function main() {
  exec('tsup')
  exec('cp -r chrome/icons dist')
  exec('cp -r chrome/manifest.json dist')
}

main()
复制代码

Problems encountered in the development process, attention points

  1. After updating the code and repackaging, you need to chrome://extensions/click the refresh button.

image.png

  1. After the plugin is installed or updated, the web page needs to be refreshed so that the latest js can be re-injected.

  2. window.postMessageWhen sending object data, an error will be reported, and the json string will be passed instead.

  3. The Google plugin needs to be specified Manifest version. I am currently using it Manifest version 2, but v2 is no longer recommended and will be abandoned in 2023. For the v3 version, you can see this migration guide

  4. The data communication of each part of the plug-in will be troublesome and easy to get confused. We can judge by passing the three values ​​of from, to and key to avoid confusion.

  5. inject-page.js, iframeWait until the page is loaded before injecting, otherwise, if you inject at the beginning, you will not be able to get dom information such as the like button

Related Links

Google Plugins are tools that, when used properly, can help us customize functionality, save time, and increase efficiency. There are still many things about Google plugins that this article has not covered. This article is just a point of entry. If readers feel that they have gained something after reading this article, please give the author a small praise! ! ! One-click three links, this time for sure! ! !

Guess you like

Origin juejin.im/post/7082766786088665118