preface

Suggest to look at the source code first, then look at the article, only front-end code, back-end interface did not write, do not ask is lazy……

The source code

The source code

The source code

Because the group owner likes to share, sometimes after bookmarking the page, the system reinstalls and the browser uninstalls… All kinds of problems, which cause bookmarks to disappear (mainly lazy)

Just write a browser plugin so that when you see a good article, you can save it to the server and share it with your team.

Purpose clear browser plug-in, when looking up relevant information to remember the previous read a political cloud browser plug-in article.

Teach you how to build your own front end tabloid system

Imitated “political cloud front – end tabloid” system is fresh out

God help me… Political cloud to the general scheme, the big brother directly finished the code……

However, this big brother is vue2 code, so let’s use vue3 + typescript to implement our own…

Project configuration

Project creation is skipped here…

Configuration items

Now that the project is created, it’s time to decorate the NPM package for development.

Copy-webpack-plugin copies files

@types/ Chrome Google browser type

  1. Modify the tsconfig. Js

    ... "Types ": ["webpack-env" // add chrome. "chrome"],...Copy the code
  2. Created vue.config.js (you can comment out the code because you don’t need it yet)

    const CopyWebpackPlugin = require("copy-webpack-plugin");
    const path = require("path");
    
    module.exports = {
      configureWebpack: {
        plugins: [
          new CopyWebpackPlugin({
            patterns: [{from: path.resolve("src/plugins/plugin-chrome.js"),
                to: path.resolve("dist/js"}]})]}};Copy the code
  3. Create manifest.json under public

    {
      "manifest_version": 2."name": "galaxy-browser-extends"."homepage_url": "http://localhost:8080/"."description": "Browser plug-in for sharing"."permissions": ["<all_urls>"."* : / / * / *"."notifications"."webRequest"]."icons": {
        "16": "icons/16.png"."48": "icons/48.png"."128": "icons/128.png"
      },
      "browser_action": {
        "default_popup": "popup.html"."default_title": "galaxy-browser-extends"."default_icon": {
          "19": "icons/19.png"."38": "icons/38.png"}},"version": "0.1.0 from"."content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
    }
    
    Copy the code

    Create icon under “public” and put a few PNG images.

  4. Modify the server startup command in package.json to facilitate our development.

    "serve": "vue-cli-service build --mode development --watch"
    Copy the code

So let’s run yarn Serve and install the plug-in.

The use of plug-in

Go to Chrome :// Extensions /, open developer mode, click Load the unzipped extension, and select Dist under the project directory. If there are no problems, you can see that the plug-in loaded successfully.

There’s no problem with…

manifest.json

Before we start writing features, let’s take a look at the basics.

The manifest. Json see for details

Each extension, installable WebApp, and skin has a JSON-formatted manifest file called manifest.json, which provides important information.

{ "manifest_version": 2, "name": "galaxy-browser-extends", "homepage_url": "http://localhost:8080/", "description": "The browser plug-in is used to share", "permissions" : [" < all_urls > ", "* : / / * / *", "notifications", "webRequest]", "ICONS" : {" 16 ": "icons/16.png", "48": "icons/48.png", "128": "icons/128.png" }, "browser_action": { "default_popup": "popup.html", "default_title": "galaxy-browser-extends", "default_icon": { "19": "icons/19.png", "38": "ICONS /38.png"}}, "version": "0.1.0", "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'" }Copy the code

Permissions: Permissions for the browser used by the plug-in. Overview of the MDN plug-in API

ICONS: ICONS 16px 48px 128px

You can add an icon to the right of the browser toolbar’s address bar. Detailed introduction

Version: plug-in version

Content_security_policy: Because we are packaged with WebPack, we will run eval MDN

interaction

Our main function function is to get the title, URL, description of the Web page

So how do we get this information?

First we need to get the tabId of the current Web page and inject JS into the page. With JS, there is still no way for our plug-in to interact directly with the current Web page. One more step is to pass messages via Message. Message passing

/** * get the tabid * of the current page@returns* /
export const ChromTabsQuery = (): Promise<number | any> = > {return new Promise((resolve, reject) = > {
    chrome.tabs.query(
      {
        active: true.currentWindow: true
      },
      (tabs: Array<chrome.tabs.Tab>): void= > {
        tabs.length ? resolve(tabs[0].id) : reject(null); }); }); };/** * Inject the script into the browser *@param tabId
 * @param path
 * @returns* /
export const ChromeTabsExecuteScript = (tabId: number, path: string) = > {
  return new Promise(resolve= > {
    chrome.tabs.executeScript(tabId, { file: path }, response= > {
      resolve(response);
    });
  });
};

/** * Send Message * to the browser@param tabId
 * @param message
 * @returns* /
export const ChromeTabsSendMessage = (
  tabId: number.message: {}
): PromiseThe < {title: string;
  link: string;
  description: string; } > = > {return new Promise(resolve= > {
    chrome.tabs.sendMessage(tabId, message, response= > resolve(response));
  });
};
Copy the code

The JS to be injected

/* eslint-disable no-undef */
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.message === "GET_TOPIC_INFO") {
    / / get the title
    const title = document.getElementsByTagName("title") [0].textContent;
    const descriptionEl = document.querySelectorAll("meta[name=description]") [0];
    // Get the description
    const description = descriptionEl ? descriptionEl.getAttribute("content") : title;
    // Send data
    sendResponse({
      title: title.trim(),
      link: location.href,
      description: description.trim() }); }});Copy the code

When we want to get the information of the Web page, we first get the tabId, and inject the corresponding Web script through the tabId. We send a Message to the script, and the script returns a Message to us.

const tabId = await ChromTabsQuery();
const status = await ChromeTabsExecuteScript(tabId, "./js/plugin-chrome.js");
if (status) {
    const result = await ChromeTabsSendMessage(tabId, {
      message: "GET_TOPIC_INFO"
    });
    const { title, description, link } = result;
    formData.title = title;
    formData.description = description;
    formData.link = link;
}
Copy the code

The end

Maybe I’m going a little bit faster, and I didn’t get into the details. Browser plugins are really a lot of stuff, but a lot of information is in English. There is really not much information in Chinese, mainly because there are relatively few people writing browser plug-ins.