This paper has participated in theProject Digg”To win a creative gift package and challenge for creative incentive money.
preface
In our work, we often need to switch the login account in the browser environment whenever we need to troubleshoot problems, run smoke cases and see the effect of the test environment. In addition, we also need to switch the proxy login account in the editor VS Code during development.
Take the business development of zhengcaiyun as an example: Accounts need to be cut in different environments such as access testing and pre-delivery, and accounts need to be cut in different roles and identities, different geographical divisions, and even when special data is checked… This makes our work full of a large number of invalid time for inputting account passwords, and also requires us to maintain additional account documents, which is very annoying.
As for the tool to quickly switch accounts in VS Code editor, some students have designed and developed it, which will be shown to you in the following articles.
This article will talk about how to the browser environment, expand the Chrome original “remember password” function, achieve rapid login and isolate the account information and functions of note labels such as ease of use, colleagues share to the test, the back-end, products, and other partners, improve the efficiency of you, hope this exploration can bring inspiration to more people.
Demand analysis
- Supports account entry and one-click login, saving input time
- You can add, delete, change, and check accounts by using personalized tag tags
- Isolate accounts in different environments to solve the interference caused by mixed use
- Easy to view and maintain data
- Friendly UI interface
Final preview
The main demonstration of the location of the plug-in, where delete and top are common functions, not demonstrated here
A key to log in
Account entry
Tag and search
The portal in the shell
The portal, written in popup/index.html, is used to provide quick access to the login pages of different environments, to clearly distinguish test, pre-release, and other environments with colors, and to record the address of the auxiliary system Luban.
The early stage of the design
Chrome Extension
Since you are logging in to a browser page on behalf of the user, you can certainly choose Chrome Extension to solve this problem.
Extensions are built on Web technologies, such as HTML, JavaScript, and CSS. They run in a separate sandbox execution environment and interact with the Chrome browser. Extensions allow you to “extend” the browser by using apis to modify browser behavior and access Web content.
Chrome will recognize the directory containing the manifest.json file as an Extension file, so we can develop a Chrome Extension project to solve this problem.
Front-end technology stack
This Chrome plugin uses the React framework for development. Other developers can also choose the technology according to their preferences.
The first version of the plug-in capability is not connected to the back end, data is stored locally.
-
advantages
- It naturally isolates data in different domain names, avoiding the defects of mixed use in testing and pre-sending environments.
- If the data is not manually deleted, the front-end can be saved for a long time, and can be viewed in the console at any time and shared with other partners.
-
disadvantages
- The inability of unified users to open accounts for different browser visitor roles will be remedied the next time they connect to the backend.
- Data will be deleted when the local cache is cleared.
Beautiful UI selection
Since the original login page of zhengce Cloud is based on the internal component library developed based on AntD, IN order to maintain the unity of visual style, I choose to continue to use our internal component library. Each team can also choose their own component library according to their own situation, or open source component library, such as Ant Design, Element UI, etc.
Easier interaction design
Since you can access Web content, the easiest thing to do is to recognize the login page without triggering any other buttons, and insert our component DOM element in the margin of the original login page to achieve the most convenient operation. We get a list of login accounts without disclosing the password. We judge the current login account according to our own label. One-click login instead of manual operation.
Project structures,
We build an empty project, configure the necessary.babelrc,.gitignore, webpack.config.js files, so that the files can support the normal use of Babel, Git, webpack, install Less and related loader to facilitate our development. The directory structure is roughly as follows:
The directory structure
.├ ── ├.md ├─ Package-Lock. json ├── SRC │ ├─ Assets ├─ contentScript # To The Web ├─ ├─ popup, ├─ ├─ webpack.config.js, manifest.json # ├─ popup #Copy the code
Manifest file manifest.json
Here is the file used to configure the basic information for the extender
- Name: extension, as shown in my extension file
- Manifest_version: Indicates the version number of the manifest.json file. As of Chrome 18, Manifest_version must be at least 2, and some of the syntax of Manifest_version 3 is only supported in Chrome 88 and beyond. Edge, Firefox and other browsers do not support it. So Manifest_version 2 is an option for more extensions.
- ICONS: ICONS displayed in the upper right corner of an extension that require images of different sizes to suit different display needs.
{
"name": "Account Saver"."description" : "Zcy account management elf ~"."version": "1.0"."manifest_version": 2."icons": {
"16": "./assets/icon.png"."48": "./assets/icon.png"."96": "./assets/icon.png"."128": "./assets/icon.png"
},
"browser_action": {
"default_icon": "./assets/icon.png".// The icon when the plug-in loads in the upper right corner of the browser
"default_title": "Account Management elf ~".// Hover icon prompt text
"default_popup":"/popup.html" // The float layer that pops up when the icon is clicked by default
},
"permissions": [
"tabs"."activeTab"."storage"."notifications"]."background": {
"persistent": false."scripts": ["./background.js"]},"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"."content_scripts": [{"matches": [
"http://*/*"."https://*/*"]."js": [ // Content script file
"/popupListener.js"]."run_at": "document_idle"}}]Copy the code
webpack.config.js
The following code to configure webpack will help us compile the style files written in HTML, JavaScript and Less, pack the static resources, and run NPM run build to get the packaged Dist file, which can be shared with the team.
const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development'.context: path.resolve(__dirname, './src'),
entry: {
popup: './popup/index.js'.background: './background/index.js'.popupListener: './contentScript/popupListener.js',},output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/'.filename: '[name].js',},module: {
rules: [{test: /\.css$/,
use: ['style-loader'.'css-loader'],}, {test: /\.less$/,
use: [
'style-loader'.'css-loader'.'less-loader'],}, {test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'.options: {
babelrc: false.presets: [
// Add preset-react to recognize the react code
require.resolve('@babel/preset-react'),
require.resolve('@babel/preset-env'),
{
plugins: ['@babel/plugin-proposal-class-properties'],},],cacheDirectory: true,},},},],},plugins: [
new HtmlWebpackPlugin({
title: 'popup'.template: './popup/index.html'.inject: true.chunks: ['popup'].filename: 'popup.html',}).new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin(['./dist/'.'./zip/']),
new CopyWebpackPlugin([
{ from: 'assets'.to: 'assets' },
{ from: 'manifest.json'.to: 'manifest.json'.flatten: true},])]};Copy the code
The core code
Content Script
Content Scripts are JavaScript files that run in the context of a Web page. With the standard DOM, Content Scripts can manipulate (read and modify) the Content of the Web page currently accessed by the browser and pass the information to the parent extension.
Insert the floating layer
Here we append elements to the body using the native JavaScript createElement() and Append () methods, inserting a float layer.
const { domain } = document;
const isZcy = domain.indexOf('zcy')! = = -1;
const userDom = document.getElementsByName('username') [0];
if (isZcy && userDom) {
// Insert a float layer on the left side of the page if the domain name is a cloud domain name and there is a name = username element (input box)
const body = document.getElementsByTagName('body') [0];
const panelWrapper = document.createElement('div');
ReactDOM.render(<AccountPanel />, panelWrapper);
body.append(panelWrapper);
}
Copy the code
A key to log in
Event()
- Constructor to create a new Event object, Event. Internet Explorer does not support this method.
event = new Event(typeArg, eventInit);
// typeArg is a DOMString that represents the name of the created event.
// eventInit Optional, accept the following fields:
// Whether bubbles support bubbles, cancelable: whether they can be cancelled, and composed: whether events trigger event listeners outside the root node of the shadow DOM
Copy the code
target.dispatchEvent(event)
- Triggers the execution of the listener function by sending an event to a specified event target. This method returns a Boolean value false as long as one of the listener functions called target.dispatchEvent, or true otherwise.
const usernameDom = document.getElementById('username');
const passwordDom = document.getElementById('password');
const { accountList } = this.state;
const { username, password } = accountList.find((item) = > item.username === handleUsername);
// This may be obsolete in the future
// const evt = document.createEvent('HTMLEvents');
// evt.initEvent('input', true, true);
// Ie does not support it
const evt = new Event('input', { bubbles: true });
// Fill the dom input box with the value
usernameDom.value = username;
usernameDom.dispatchEvent(evt);
passwordDom.value = password;
passwordDom.dispatchEvent(evt);
// Simulate the user clicking the login button
const loginBtn = document.getElementsByClassName('login-btn') [0];
loginBtn.click();
Copy the code
Development assistance
One-click reload: Extensions Reloader
Even if Webpack is configured with hot updates, the JavaScript code packaged by the plugin cannot be hot loaded after it is updated. You can go to Chrome :// Extensions/and reload it by clicking the button in the image below. Or install the Extensions Reloader plug-in and click the button to reload.
Install extension files
Chrome allows you to install extension files from both Chrome App Market and Local Files sources. Go to Chrome :// Extensions /, open developer mode, click load unzipped extension, and select our local files. Edge is also available.
The next stage
The target
- Data is stored on the back-end to avoid data loss.
- Share the data to a front-end VSCode plug-in for use by a fast local agent.
- Added user login function to solve the problem of sharing visitor identity data with the same user.
- Isolate the service team to avoid Tag mixing and the inconvenience of full account search.
- Open Chrome visitor identity and log in with one click, and operate multiple accounts at the same time for easy testing.
Design Direction: Add the login function for users of the plug-in. The login scope is defined by domain account, password and service group. The same service group shares the test account, bound service label, and application associated with the service group. During front-end local development, the account obtained by the project is pulled by the business team to which the current application belongs.
E – R diagram design
Reference documentation
Chrome Developers
Recommended reading
E-commerce minimum inventory – SKU and algorithm implementation
What you need to know about project management
Backflow redraw of browser rendering
Anti-shake throttling scenario and application
Open source works
- Political cloud front-end tabloid
Open source address www.zoo.team/openweekly/ (wechat communication group on the official website of tabloid)
- skuDemo
Open source addressGithub.com/zcy-inc/sku…
, recruiting
ZooTeam, a young passionate and creative front-end team, belongs to the PRODUCT R&D department of ZooTeam, based in picturesque Hangzhou. The team now has more than 50 front-end partners, with an average age of 27, and nearly 30% of them are full-stack engineers, no problem in the youth storm group. The members consist of “old” soldiers from Alibaba and netease, as well as fresh graduates from Zhejiang University, University of Science and Technology of China, Hangzhou Electric And other universities. In addition to daily business docking, the team also carried out technical exploration and practice in material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of front-end technology system.
If you want to change what’s been bothering you, you want to start bothering you. If you want to change, you’ve been told you need more ideas, but you don’t have a solution. If you want change, you have the power to make it happen, but you don’t need it. If you want to change what you want to accomplish, you need a team to support you, but you don’t have the position to lead people. If you want to change the pace, it will be “5 years and 3 years of experience”; If you want to change the original savvy is good, but there is always a layer of fuzzy window… If you believe in the power of believing, believing that ordinary people can achieve extraordinary things, believing that you can meet a better version of yourself. If you want to be a part of the process of growing a front end team with deep business understanding, sound technology systems, technology value creation, and impact spillover as your business takes off, I think we should talk. Any time, waiting for you to write something and send it to [email protected]