1. Basic introduction

Chrome extension, also known as Chrome plug-in, is a software developed with Web technology to enhance browser functions. It is actually a.crx compression package composed of HTML, CSS, JS, images and other resources.

The Chrome plugin doesn’t have strict project structure requirements, it just requires a manifest.json file in the root directory.

You can access the Plugin Management page from the top right menu -> More Tools -> Extensions, or directly enter Chrome :// Extensions in the address bar. The diagram below.

If you select Developer mode, you can folder the plugin directly, otherwise you can only install. CRX files. Chrome requires the plugin to be installed from its Chrome App Store, and you can’t install it directly from any other website, so you can actually unzip the CRX file and load it directly from developer mode.

During development, any changes to the code must be reloaded by pressing Command+R on the plug-in management page, preferably refreshing the page in case. You can also click the refresh button of the plug-in directly, and the local code can be synchronized. The diagram below.

Second, core introduction

2.1 the manifest. Json

{"name": "SourceMapRedirect", // Plugin name" description": "Try to redirect SourceMapRedirect to FTP server", // plugin description" version": "1.0", // Plug-in version" Manifest_version ": 2, // Manifest file version, mandatory "permissions": "WebRequest ", "webRequestBlocking", "<all_urls>", It can also be written as "http://*/*", "https://*/*", and can be described as "declarativeNetRequest"], "background", which can be accessed through executeScript or insertCSS: {// "scripts": ["background.js"] // "page": } "content_scripts": [{//"matches": [{//"matches": [" http:// * / * ", "https:// * / *"], / / "< all_urls >" means to match all address "matches" : [" < all_urls > "], / / multiple JS injection in sequence "JS" : ["js/jquery-1.8.3.js", "js/content-script.js"], // Javascript injection can be arbitrary, but CSS should be paid attention to, because it can affect the global style "CSS ": [" CSS /custom.css"], // Time for code injection, // Optional values: "Document_start ", "document_end", or "document_idle" "/images/icon32.png", "32": "/images/icon32.png", "48": "/images/icon32.png" "/images/icon48.png", "128": "/images/icon128.png" }, "action": { "default_popup": "Popup.html ", // click on the popover page "default_icon": {// Click on the popover page "16": "/images/get_started16.png", "32": "/images/get_started32.png", "48": "/images/get_started48.png", "128": "/images/get_started128.png"}}, "options_page": "options.html", // the plugin configuration page before Chrome40 was written "options_ui": {// Add a default style to the page: "options. HTML ", "chrome_style" is recommended: "Rule_resources ": [{"id": "ruleset_1", "enabled": [{"id": "ruleset_1", "enabled": true, "path": "rules.json" }] }, }Copy the code

I use Version 2 of Manifest_Version. Currently, there are version 3 of Manifest_version, and version 3 is officially recommended. But since the webRequest API I wanted to use had support problems with 3, I used version 2. And at present, most examples on the official website are version 2, so for beginners, version 2 is relatively more friendly.

Content-scripts is a form of the Chrome plugin that injects scripts to pages. It shares the DOM with the original page, but not the JS, and can only access the INJECTED JS of the page (for example, a JS variable) through its injected JS. Content-scripts does not access most chrome.xxx. API, except for the following four:

  • chrome.extension(getURL , inIncognitoContext , lastError , onRequest , sendRequest)
  • chrome.i18n
  • chrome.runtime(connect , getManifest , getURL , id , onConnect , onMessage , sendMessage)
  • chrome.storage

2.2 background

Background is a resident page that has the longest lifetime of any type of page in the plug-in, opening as the browser opens and closing as the browser closes, so it usually places global code that needs to run all the time. It has high permissions and can call almost all Chrome extension apis (except DevTools)

It can be unrestricted cross-domain, that is, it can access any website across domains without requiring CORS to be set.

You can specify a web page via Page, or you can specify a JS directly via scripts, and Chrome will automatically generate a default web page for this JS.

Need of special note is, although you can use the chrome – the extension: / / XXX/background. The HTML directly open the background page, but you open the page background and real has been run in the background of the page is not the same, in other words, You can open an infinite number of background.html files, but there’s only one that actually lives in the background, and you’ll never see its interface, only debug its code.

2.3 the event – pages

In view of the long background life cycle, mounting the background for a long time may affect the performance, so Google makes another event-Pages. In the configuration file, the only difference between it and background is that it has a persistent parameter:

{
  "background": {
    "scripts": ["event-page.js"],
    "persistent": false
  }
}
Copy the code

Its life cycle is: loaded when needed, closed when idle, what is needed? First installation, plug-in update, content-script sending messages to it, and so on.

In addition to the configuration file changes, there are also some minor changes in the code, which should be explained briefly. Background is not a performance drain in general.

Request forwarding API

// background.js chrome.webRequest.onBeforeRequest.addListener( (info) => { if (info.url.includes(".map")) { console.log("source map files: " + info.url); } return {redirectUrl: XXX} // address you want to redirect // Return {cancel: true}} if you want to intercept the request, // filters {urls: [ "<all_urls>" ] }, // extraInfoSpec ["blocking"] );Copy the code

I actually originally wanted to deal with security issues for Sourcemap. You want to upload the Sourcemap file to the Intranet and delete it from the public network. Later, the sourcemAP request from the public network is forwarded to the internal network during debugging, so as to ensure security and facilitate debugging.

The interception and forwarding of requests is very easy to implement when a fatal problem is found in the actual implementation. However, sourcemap requests automatically made by Google Browser according to the comment code # sourceMappingURL=bundle.js.map at the end of JS cannot be caught through the webRequest API. The Declarative_net_REQUEST API was also tried, but was also untouchable. I guess the reason is that Google Chrome itself ignores sourcemap’s automatic requests in the Network panel (note that Google Chrome only automatically requests sourcemap files when the development panel is open), so it makes sense that the API doesn’t capture packages (that’s how I convinced myself). .). Of course, enter the sourcemap file address into the address bar. Unsolicited requests can be caught in the Network panel, as well as the Chrome API.

For these reasons, it is impossible to implement sourcemap forward requests in Chrome. But there are a few things I’ve learned about the Chrome plugin, which makes it very easy to forward captured requests.

The final solution: Use the Whistle script to automatically add forwarding rules.

Since tools like Whislte and Charles can catch sourcemap requests automatically sent by Google, it’s easy to write rules and forward them. For easy maintenance, add the Whistle script to your code so that you can add forwarding rules as soon as you run the script.

// .whistle.js const pkg = require('./package.json'); let projectDomains = ['XXX', 'XXXX', 'XXXX'] let sourceMapFolder = 'XXXXX' let ftp_ip = 'XXXXX' exports.name = '[${pkg.name}] localenvironment configuration'; exports.rules = ` /[http|https]://[^/]*(${projectDomains.join('|')})/(.+.map)/ ${ftp_ip}/${sourceMapFolder}/$2 `;Copy the code
// package.json { ... "scripts": { ... "add_whistle_config": "w2 add --force", ... }... }Copy the code

Reference documentation

www.cnblogs.com/liuxianan/p…

www.bookstack.cn/read/chrome…

Developer.chrome.com/docs/extens…

Github.com/GoogleChrom…