Record a front-end “Chrome plug-in” basic actual combat sharing meeting (recommended Collection) (Part 2)

Time:2021-9-6
Undertake the above

10、 Right mouse button menu

You need to add menu permission to the permission firstmanifest.json "permissions": ["contextMenus"],.
The specific code to add the menu, we put it inbackground.jsInside the file

chrome.contextMenus.create({
    Title: "dare you click on me",
    Onclick: function() {alert ('clicked someone ');}
  });

Record a front-end

After clicking here, the click method defined by us will be called
Record a front-end

The second way: we make the menu into options, such as three modes for users to choose one

chrome.contextMenus.create({
  Title: "option 1",
  "type": "radio",
  Onclick: function() {alert ('1 ');}
});
chrome.contextMenus.create({
  Title: "option 2",
  "type": "radio",
  Onclick: function() {alert ('2 ');}
});
chrome.contextMenus.create({
  Title: "option 3",
  "type": "radio",
  Onclick: function() {alert ('3 ');}
});

Record a front-end

Of course, there are multiple choices

chrome.contextMenus.create({
  Title: "option 1",
  "type": "checkbox",
  Onclick: function() {alert ('1 ');}
});
chrome.contextMenus.create({
  Title: "option 2",
  "type": "checkbox",
  Onclick: function() {alert ('2 ');}
});
chrome.contextMenus.create({
  Title: "option 3",
  "type": "checkbox",
  Onclick: function() {alert ('3 ');}
});

Record a front-end

The second category of the right-click menu

A menu that is displayed only when something is selected

chrome.contextMenus.create({
    Title: 'selected:% s', //% s indicates the selected text
    Contexts: ['selection '], // this right-click menu appears only when Chinese text is selected
    onclick: function(params)
    {
     Alert ('query something ')
    }
  });

The first menu and the second menu are created at the same time. When displayed, only one corresponding situation is displayed
Record a front-end

11、 Content_ The culprit of ‘malicious advertising’?

  1. What is content_ scripts

For example, when visiting a page, I will inject my code into the JS code of the page, which is content_ The role of scripts, I can or the DOM structure of the current page and document

  1. Configure import content_ scripts

manifest.json, the following paragraph means that all pages are inserted with the code logic of “content / index. JS”

  "content_scripts": 
    [
        {
            "matches": ["<all_urls>"],
            "js": ["content/index.js"],
        }
  ],
  1. Timing of insertion

content_ Scripts configuration is an array type, so it means that it can configure multiple groups of logic, and the time when the code takes effect can also be configured;
"run_at": "document_start"The time when the DOM first started loading
"run_at": "document_end"DOM loading is complete (DOM can only be obtained at this time)
"run_at": "document_idle"When the page is idle (it is him by default)

Let’s write a random piece of code

Console.log ('I injected ')
Console.log ('Get window ','window')
Console.log ('Get document ','Document')

Then update the component and see the effect on different pages:
Record a front-end
Record a front-end

Each website will be executed when it is loaded, but some precautions are in Article 7. Don’t forget to take a look

  1. Can the dom of the insert operation get the variables of the source JS?

Here we set up an HTML page to verify our problems one by one

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  < div id = "Wo" > I will get < / div >
  <script>
    Var CC = 'golden hair'
  </script>
</body>
</html>

Add logic in the plug-in

Console.log ('I injected ')
Console.log ('Get window ','window')
Console.log ('Get document ','Document')
Console.log ('Get CC ', window. CC)
Console.log ('Get DOM ', document. Getelementbyid ('wo'))

Record a front-end

In fact, it is not recommended that we change the user’s JS code logic. This is not recommended for both security factors and the self consistency of the overall logic. The method of accessing JS variables is not introduced here. If you are interested, you can check the official website

  1. Configure CSS

We can also insert CSS code into the page to change the appearance of the page
staymanifest.jsonMake modifications

"content_scripts": 
    [
        {
          "matches": ["<all_urls>"],
          "js": ["content/index.js"],
          "css": ["content/index.css"]
        }
  ],

CSS can affect all DOM structures on the page, including the original Dom and the DOM structure we inserted later
content/index.cssinside

#wo {
  border: 1px solid red;
}

The page effect is as follows
Record a front-end

  1. Inserting malicious ads and modifying DOM

Now that we have obtained the DOM, we can certainly modify the DOM or add a new DOM to your page

Modify element content
Document. Getelementbyid ('wo '). InnerText =' modified content '

Add element to page

const div = document.createElement('div');
div.className = 'cc'
Div.innerhtml = "if you are a brother, come to Kanwo"

document.body.append(div);

div.addEventListener('click', ()=>{
  Alert ('collect 999999 ')
})

The style should also look better

.cc {
  display: flex;
  color: white;
  position: fixed;
  align-items: center;
  justify-content: center;
  background-color: black;
  right: 0;
  bottom: 0;
  width: 300px;
  height: 200px;
}

The actual effect is like this in the picture
Record a front-end

  1. Permission note:
    ① : this method is invalid on the plug-in extension page!!! Please go to the normal page for debugging!
    ② : unable to get the variable of this page
    ③ : page change will not trigger re execution, and only page refresh will trigger re execution

12、 Devtools creates its own panel to monitor every move of the web page

Let me give you an example. What is this function
Record a front-end

It can be divided into two parts, devtools_ Page can be used to operate the tab column, and panel is the HTML structure and logic in each specific tab

Create a label
staymanifest.jsonAdd such a section of configuration in
"devtools_page": "devtools/index.html"
In this file, we define the reference of JS

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script></script>
</body>
</html>

It is written in the index.js file

//Create a custom panel. The same plug-in can create multiple custom panels
//The parameters are: panel title, icon (no need to write), page to be loaded, and callback after successful loading
Chrome. Devtools. Panels. Create ('occupied by me ', null,' panel / index. HTML ', function())
{
  //The console must be closed and then opened before it can be displayed. There is no problem with Chinese
  Console.log ('custom panel created successfully! ');
  //He is also an HTML page, so he can check it again
});

Record a front-end

It must be noted that this must F12 close the console and then open the console to take effect. Don’t be trapped if it’s useless to refresh!!

Record a front-end
Record a front-end

This is a nested console. Isn’t it amazing? It’s a little different from our usual understanding.

So the problem is, the first console can actually be regarded as a page. What about his HTML?? In fact, it depends onpanel

panel/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script></script>
</body>
</html>

panel/index.js

Console.log ('I'm the console of the panel page, Hello everyone ')

Record a front-end

Since it is equivalent to a page, you can certainly manipulate its DOM structure. Let’s implement the following
Manipulate his DOM

const nr = document.getElementById('nr');
const bt = document.getElementById('bt');
bt.onclick = function(){
  Nr.innerhtml = "content changed"
}

The result is certainly clear
Record a front-end
Record a front-end

13、 Get reviewed page resources

One of the main functions of the panel is to give a processing and analysis scheme based on the situation of the page. How do we communicate with the reviewed page?
panel/index.js

chrome.devtools.inspectedWindow.getResources ((res)=>{
   Console.log ('obtained resource elements', RES)
  const obj = {}
  res.forEach((el, i) => {
    obj[el.type] = el.url + `xxxxxxx-> ${i}`
  });
  Console.log ('object type ', obj)
 })

Simple pages we define:
Record a front-end

Complex web pages:
Record a front-end

It can be seen from the above information that the API for obtaining the resources of the reviewed page is mainly to obtain the loaded resource types and connections, which are classified according to the main types
We can use this API to analyze the resource structure loaded by the project

14、 Get reviewed page DOM

This is a bit of a detour. You can also try other methods to obtain dom. Here is the eval method
Let’s start with a basic example

chrome.devtools.inspectedWindow.eval("window.location", (res, isException)=>{
   Console.log ('execution result is: ', res, isexception)
 })
  1. chrome.devtools.inspectedWindow.evalIs a statement executed on the reviewed page
  2. The first parameter is the statement to be executed
  3. Res is the return value of the executed statement
  4. Isexception is whether an error is reported during execution. If an exception occurs, it is true
  5. It is worth noting that res only accepts valid JSON objects, which is an important ruleVery, very important!

For the first time, you might write like this

chrome.devtools.inspectedWindow.eval(`document.getElementsByTagName('*')`, (res)=>{
    Console.log ('execution result is document:, RES)
  })

You will find something strange printed out, as shown in the figure below
Record a front-end
Record a front-end

It’s time to test your basic skills. Do you know why? Think for yourself

The answer is here

Record a front-end
It turned out that when we got the structure, we did JSON processing, so we understood that the DOM structure cannot be taken over for processing. We should handle it in the eval method and then take it over. We have the following code

chrome.devtools.inspectedWindow.eval(`[...document.getElementsByTagName('*')].map((item)=>item.localName)`, (res)=>{
  const obj = {}
  res.forEach((item)=>{
    obj[item] = obj[item]?(++obj[item]):1;
  })
  Console.log ('execution result is: ', obj)
})

Record a front-end
Record a front-end

That is, put the processing logic in Eval and return the processed results

15、 Block requests for reviewed pages

This is also a very common function. Each user request is analyzed and listed

chrome.devtools.network.onRequestFinished.addListener( (res) => {
  Console.log ('request body: ', RES)
});

Record a front-end
Record a front-end

If we have all the basic information requested, we can play a lot of tricks

16、 Why should all permissions be configured in the main file

This idea is quite interesting. We can use it for reference when writing code. First write the required permissions in the configuration file, so that when using your extension, you can first ask the user whether to give you relevant functions. If the user does not give relevant functions, the object of relevant functions will be empty, so as to achieve the function of configuring permissions from the source

17、 Interesting practical imagination (bug monitoring system)

The bugs mentioned in the test need to be viewed on the bug platform. Every time I switch pages, can I interact with the API related to the bug platform? For example, if there is a bug on a page, the icon in the upper right corner will be displayed in red and indicate the number or amount of bugs
Combined with the pop-down, you can perform basic operations, processing, completed, and other status modifications on the bug

18、 Interesting practical imagination (page theme modification system)

Insert the DOM structure in the page and click Change theme to change the provincial color coefficient of the DOM structure of the industry
Or write the options in the radio item of the menu on the right and let the user choose, content_ Script updates the page when it detects that the configuration in the cache has changed

19、 Interesting practical imagination (monitoring the interface of repeated requests within the project)

If there are repeated calls to an interface in the project, point out the interface, and then analyze why there are repeated calls. If it is not a problem, put the interface in the white list without monitoring

20、 Interesting practical imagination (VPN agent)

Since you can get the user’s request information, you can use the obtained URL to proxy the request address. I won’t elaborate on this function here, because many VPN plug-ins are implemented in this way

end

Next, I’m going to do articles related to 3D and micro front-end. I hope you can give me more support
That’s all this time. I hope to make progress with you