当前位置:网站首页>Take you to understand the working process of the browser

Take you to understand the working process of the browser

2022-06-23 21:43:00 Great inventor

( One ) process

A process is a running instance of a program ,

Every time you start an application , The operating system will create a block of memory for this program , Used to store code 、 Data data 、 A main thread that executes tasks , We call such a running environment process .

A process shuts down , The operating system will reclaim the memory space allocated for the process

( Two ) Threads

A thread is attached to a process , And the use of multithreaded parallel processing in the process can improve the efficiency of operation .

Process and thread diagram .png

The relationship between processes and threads : ( The process is a train , Threads are per car )

  1. An error occurred in the execution of one of the threads in the process , Will cause the whole process to crash
  2. Threads share common data in the process .
  3. When a process is shut down , The operating system reclaims the memory used by the process .
  4. The content between processes is isolated from each other
( 3、 ... and )、 Browser multi process era
  1. A browser main process : It is mainly responsible for displaying the page layers generated by the rendering process 、 User interaction 、 Child management process , Provide storage and other functions
  2. One GPU process : Responsible for graphics processing
  3. A network process : Responsible for downloading network resources
  4. Multiple rendering processes ( The core of the browser , Commonly known as the browser kernel ):
*  By default , Every tab Page a process , They don't influence each other   --  A special case 1: Such as multiple blanks tab Will merge into one process ;undefined--  A special case 2: A new tab is opened from one tab , When the new tab and the current tab belong to the same site , Then the new tab will reuse the rendering process of the current tab 
*  The core task is to  HTML、CSS  and  JavaScript  Convert to web page layer , Notify the browser main thread to display the interface ;
*  The rendering process runs in sandbox mode 
*  The rendering process contains the following threads :  (1).GUI Rendering thread undefined(2) Javascript Engine threads undefined(3)  Event trigger thread ( Belongs to the browser instead of JS engine )undefined(4) Timing trigger thread undefined(5) asynchronous http Request thread undefined(6) Composite thread undefined(7)IO Threads : Process communicates with other processes undefinedGUI Rendering thread and JS Engine threads are mutually exclusive , Cannot be executed together 
  1. Multiple plug-in processes : Responsible for running plug-ins in the page ; It also runs in sandbox mode

Between the processes IPC To communication

Two 、 Browser rendering process

First step , analysis : The main thread starts parsing HTML
  1. Browser received HTML,HTML The parser starts parsing HTML, Generate DOM Tree, And saved in the browser memory undefined-- At the same time, start a pre parsing thread , Used for analysis HTML The file contains Javascript、 CSS 、Img And so on , Notify the network process to load these resources in advance
  2. Parsing encountered CSS(style、 inline 、link),CSS The parser starts to CSS To analyze , Generate CSSOM( namely styleSheets)
  • Pattern calculation :(css Inheritance of style 、 Rules such as stacking )
  • Convert attribute values in styles , Such as color: red; => color: rgb(255, 0, 0)
  • To calculate the DOM The specific style of each node
  1. encounter <script> , The rendering thread stops parsing the remaining HTML file , wait for Javascript Resource loading ,Javascript After the engine executes the script ,HTML Let's continue with the analysis
JavaScript Scripts depend on style sheets , Will wait first CSS After the file is loaded and parsed, execute , therefore Javascript The style of the element is finally effective
javascript It will block HTML Parsing and page rendering

css Analytic and HTML Parse parallel , It won't block HTML analysis , But it will block page rendering ( however Javascript perform , It can lead to CSS The parsing of HTML Time of resolution )

The second step , Generate Layout Tree( Layout tree )

according to DOM and styleSheets Generate LayoutTree Layout tree ( Render tree ), All invisible elements are ignored , Such as head label ,

display:none The elements of ,script Labels etc.

Layout tree .png

The third step , Layout calculation
  • The rendering engine calculates the geometric position of each element in the layout tree , And save the calculation results in the layout tree ,
  • The output of the layout phase is what we often call the box model , It accurately captures the exact location and size of each element within the screen
Step four , layered , Generate layer tree

The rendering engine generates a layer tree based on the layout tree ,

Step five , draw
  • The main thread generates a drawing list according to the layer tree , Give it to the synthesis thread
  • The compositing thread divides the layer , Generate fixed size tiles
  • The composition thread gives priority to... According to the blocks near the viewport GPU process
Step six , Rasterize , Generate bitmap

GPU The process generates bitmaps according to different blocks , And the composite thread

Step seven , synthesis
  • After the composite thread receives each block bitmap , Issue the composite command , To the browser main process
Step eight , display
  • The browser main process then displays the interface

l Browser rendering flowchart .png

Special cases in the rendering process :

1. rearrangement ( backflow ):

Refers to the modification of element geometric attributes , Such as location 、 Size 、 Content 、 Structural isovariation , Cause a change in the geometric position of the element , The browser needs to recalculate the style 、 Build a layout tree , A series of sub phases after the start , This process is called rearrangement .

Rearrangement requires updating the complete rendering pipeline , So the cost is the biggest .

The situation that triggers the rearrangement :(Javascript operation DOM, Cause different rendering pipelines to work again )

  • Add or remove visible DOM Elements
  • Element position changes
  • Element size change
  • Element content changes
  • Changing the font size will cause reflow
  • Page renderer initialization
  • Browser window size changes
  • When getting some properties , Browsers also trigger reflow in order to get the right value , This makes browser optimization ineffective , Include undefined(1) offset(Top/Left/Width/Height)undefined(2) scroll(Top/Left/Width/Height)undefined(3) cilent(Top/Left/Width/Height)undefined(4) width,heightundefined(5) Called getComputedStyle() perhaps IE Of currentStyle
2. Repaint :

The appearance style of the element is modified , It will not change the geometric position , Go directly to the drawing stage , Generate draw list , And then a series of sub phases after that , This process is called redrawing . Like the background color 、 Border color , Text color, etc

Redrawing saves the layout and layering stages , So the execution efficiency will be higher than the platoon operation . Rearrangement inevitably leads to redrawing , But redrawing does not necessarily lead to rearrangement
3. Direct synthesis :

Change a property that neither layout nor draw , Direct partition block stage , Then give it to the browser. The main process is not displayed online , This process is called direct synthesis .

Such as transform:translate(100px, 100px)

Relative to redrawing and rearranging , Direct synthesis can greatly improve the efficiency

Reduce rearrangement ( backflow )、 Repaint , Method :

  • many times dom Operation synthesis once , The batch operation , for example createDocumentFragment,vue Frame virtual DOM and diff Algorithm
  • Use class Operation style , Instead of frequent operation style
  • When working with animation , Use will-change and transform Make optimization undefined stay css Use in will-change, The rendering engine generates a separate layer for this element

3、 ... and 、JavaScript Execution mechanism

( One )JavaScript Code execution process
First step , The code to compile :JavaScript The engine compiles the code , And keep it in memory

The compilation result is two parts : Execution context 、 Executable code

showName();// function showName Be performed 
console.log(myname);//undefined
var myname = ' The small white '
function showName() {
    console.log(' I am a little white ');
}

The execution context at compile time is as follows :( Variable environment section )

{
  showName: xxx, //showName  The reference address of the function in heap memory 
  myname: undefined
}

The executable context is as follows :

  showName();
  console.log(myname);//undefined
  myname = ' The small white '
  • Execution context : yes JavaScript Running environment when executing a piece of code undefined Each execution context contains the following sections :
1.  The variable environment 
2.  Lexical environment 
3.  The external environment , That is, the external reference of the variable in the current execution context , Used to point to an external execution context , Also known as  outer
4. this,this The point of is the calling method of the current function   - Direct calls to global objects window ( In strict mode, it is undefined)undefined- Call... By object ,this Point to the object undefined- adopt apply、call、bind And other method calls point to the first parameter object undefined- In the arrow function this Pointing to the outer function this( Parsing the arrow function does not create an execution context )
  let userInfo = {
      userName: " The small white ",
      age: 18,
      sayHello: function () {
      setTimeout(function () {
         console.log(`${this.userName}, Hello `)   //undefined
       }, 100)
   }
}
userInfo.sayHello()

Modify a function this The way to point :

  • Cache external this, Such as var _this = this;
  • Use the arrow function
  • Use app、call、bind change this Point to
The second step , Execute executable code

problem :

  1. var Variable Promotion undefined Compile time variable declaration Promotion , And the initialization value is undefind,
  2. Function declaration promotion
  • Multiple functions with the same name are declared at the same time , The function declared later will overwrite the function declared earlier
  • Function declarations take precedence over variable promotion , The variable name is the same as the function declaration name , Use the function name

solve : introduce let、const、 Block level scope

( Two ) Function execution ( call ) The process
  1. Execution context stack :undefined Used to manage the execution context , Last in, first out
  • Global execution context : Execute global code to generate a global execution context , There is only one , Accompany the entire life cycle of the page
  • Function execution context : Executing each function generates a function execution context , There can be multiple , When function execution ends , The execution context of the function will be destroyed

A piece of code parsing is completed , That is, the execution context is created , Immediately execute the executable code

var a = 2
function add(b,c){
  return b+c
}
function addAll(b,c){
  var d = 10
  result = add(b,c)
  return  a+result+d
}
addAll(3,6)

First step , Parse global code , Create a global execution context , Push the call stack , And execute executable code globally

Execution context stack .png

The second step , Execute to addAll Invocation time , Generate addAll The execution context of the function , Push in context , Concurrent execution addAll Executable code inside a function

Execution context stack .png

The third step , Execute to add Function call , Generate add The execution context of the function , Push the call stack

Execution context stack .png

perform add Executable code inside a function ,return result , then add Function execution context destruction , Pop up the call stack

Fourth parts , perform addAll Subsequent executable code ,return result ,addAll Function context destroy , Pop up the call stack , Finally, only the global execution context is left , Accompany the whole life cycle of the page

problem : Stack overflow ( Recursive function )

( 3、 ... and ) Scope 、 Scope chain 、 Closure
1. Scope : Refers to the range of variables and functions that can be accessed
  • Global scope : Anywhere in the code can be accessed , That is, variables and functions in the global execution context can be accessed anywhere , The life cycle is accompanied by the life cycle of the page .
  • Function scope : Variables or functions defined inside a function can only be accessed inside a function , After function execution , Variables defined inside the function will be destroyed along with the function execution context ( Except closures )
  • Block level scope { }

var 、 let、const The difference between :

  1. var:undefined-- stay javascript When parsing , Declare and initialize elevation , No error will be reported before the declaration , The value is undefined;undefined-- Stored in the variable environment in the execution context undefined-- You can declare the same variable multiple times , The latter value overrides the previous value ;undefined-- Block level scopes are not supported
  2. let :undefined-- To declare a variable , In parsing , The statement will elevate , But initialization does not promote , An error occurred during the visit before the declaration ;undefined-- Stored in the lexical environment of the upper and lower execution undefined-- Cannot declare more than once within the same scope ;undefined-- Supports block level scopes
  3. const :undefined-- Used to declare a constant , You can't modify it again undefined-- The statement will elevate , But initialization does not promote , An error occurred during the visit before the declaration ;undefined-- Stored in the lexical environment of the upper and lower execution undefined-- Cannot declare more than once within the same scope ;undefined-- Supports block level scopes
function foo(){
    var a = 1
    let b = 2
    {
      let b = 3
      var c = 4
      let d = 5
      console.log(a); //1
      console.log(b); //3
    }
    console.log(b) ;//2
    console.log(c); //4
    console.log(d); // Report errors :d is not defined
}   
foo()
2. Scope chain : Variable lookup looks up the execution context pointed to by external references layer by layer along each scope , Form a chain , Scope chain

The scope of a function is determined by the lexical scope

Lexical scope : The scope is determined by the position of the function declaration , It has nothing to do with how the function is called

3. Closure :

When the function is finished , The defined variables in the function body will be destroyed immediately with the function execution context , But when an external function contains an internal function , And the internal function uses the variables defined in the external function , These variables will not be destroyed , Still in memory , These variables and internal functions form closures

The conditions for the formation of closures :

  1. There are internal functions in external functions
  2. Variables defined in external functions are used in internal functions
 function foo() {
    var myName = " The small white ";
    var age = 18;
    function sayHello(){
       console.log (` Hello , My name is :${myName}, This year, ${age}`)
    }
    return sayHello;
}
let hello = foo();
hello()
// myName and age Namely foo Closure of function 
  • Reasons for closure formation :undefinedJavascript In the code compilation phase , Internal function encountered when ,JavaScript The engine will do a quick lexical scan of the internal functions ,undefined It is found that the internal function references the variables defined by the external function , So create a new one in the heap space “closure” The object of , Used to save variables used by internal functions , This closure Objects are closures
  • When closures are recycled ?
1.  When the function referencing the closure is a global variable , Closures are always stored in memory , Until the page closes 
2.  When the inner function of the reference closure is a local variable , After the execution of the internal function , The inner function will be destroyed immediately , The next time JavaScript  When the engine performs garbage collection , Judge not to use , Then destroy the closure , Reclaiming memory 

problem : Memory leak ( The reclaimed memory was not reclaimed in time )

( Four )Javascrip Garbage collection mechanism
1. Javascript Memory mechanism of
  • Stack memory : Store basic type data ( The call stack , Execution context stack )undefined When a variable is a reference type , What is stored is the reference address of the reference type ( Number )
  • Heap memory : Store reference type data
  • Code space : Store executable code
2. Javascript Garbage collection mechanism

After the data is used , It's no longer necessary , It's called junk data , Garbage data should be destroyed in time , Free up memory , Otherwise, there will be a memory leak .

  • Manual recycling , If the variable is set to null
  • Automatic recovery

(1) Stack memory recycling

When Javascript Code execution , A pointer to record the current execution state ( be called

ESP), Pointer to the current execution context , Completed before the current function code , The pointer moves down to the execution context of the next function to be executed , The current execution context pops up the call stack for destruction , This process is the process of memory recovery of the function stack

 function foo(){
    var a = 1
    var b = {name:" Geek state "}
    function showName(){
      var c = 2
      var d = {name:" Geek time "}
    }
    showName()
}
foo()

The call stack .png

(2) Heap memory recovery

Garbage collector :

  • Main garbage collector : Responsible for recycling long-lived garbage data ( Old generation garbage data )
  • Secondary garbage collector : Responsible for recycling garbage data with short lifetime ( New generation garbage data )

First step , Mark active and inactive objects in heap memory

  • The object of activity : Data still in use
  • Inactive objects : Junk data

The second step , Reclaim memory occupied by inactive data

After all marking is completed , Uniformly clean up all objects marked as recyclable in memory

The third step , Do memory management

( 5、 ... and ) Browser's event loop mechanism

Each rendering process has a The main thread , Handle the following events :

  • Rendering Events ( Such as analysis DOM、 Calculate layout 、 draw )
  • User interaction events ( As a mouse click 、 Scrolling pages 、 To enlarge or shrink, etc )
  • JavaScript Script execution events
  • Network request complete 、 File read / write complete event

Message queuing and looping mechanisms ensure that pages run in an orderly manner

1. Task queue : It's a data structure , Used to place the task to be performed , fifo

Synchronization task : Directly enter the task executed by the main thread , Only the previous task was completed , To perform the next task

Asynchronous task : Implement with callback function , Queue up in other task queues first , Wait for the synchronization task to complete , This task is then executed on the main thread , Divided into macro tasks 、 Micro task

Macro task queue : Macro task execution queue , The task to be executed in the callback function

Micro task queue :JavaScript Execute a script ,V8 The engine will first create a global execution context , At the same time, it will also create a special for V8 The micro task queue used internally by the engine

(1) Macro task : The hosting environment is the task assigned by the browser

Macro task There are mainly the following :

  1. setInterval、setTimeoutundefined-- setTimeout The actual execution time of the callback function >= Set the time , The reason is that the execution time of other tasks in the message queue
  2. XMLHttpRequest
(2) Micro task :JavaScript Engine initiated tasks , The execution time is before the end of the current macro task

Javascript Script execution itself is a macro task , The macro task also contains the synchronization task 、 Micro task 、 Macro task

console.log(1);
setTimeout(()=>{
  console.log(3);
  Promise.resolve(4).then((data) => {
      console.log(data)
  })
  setTimeout(() =>{
     console.log(5)
  },0)
}, 0)
Promise.resolve(2).then((data) => {
    console.log(data)
})
// Execution results :1, 2, 3,5

Micro tasks and macro tasks are bound , Each macro task is executed , Will create its own micro task queue

Micro task is earlier than macro task

The execution time of the micro task will affect the duration of the current macro task

Micro tasks mainly include :

  1. MotutaionObserver
  2. Promiseundefined(1) Promise Three states of undefinedpending( Pending status )、fulfilled( Execution success status )、rejected( Execution failure status )

(2) The executed state is irreversible , It won't change again

or pending ->fulfilled

or pending -> rejected

(3) Promise Realization principle :

- Callback function delay binding ( Micro task )

- The return value of the callback function penetrates ,then The return value in the callback function , Can penetrate to the outermost layer

- error “ Bubbling ”, Call... By chain then、catch, No matter what level you make a mistake , Metropolis “ Bubbling ” to catch

// Encapsulate a function , Simple simulation promise  
function MyPomise(executor) {
      let _this = this;
      let _onResolve = null;
      this.then = function (onResolve) {
          _onResolve = onResolve;
      }
      this.resolve = function (value) {
        // This is used here setTimeout Simulate delayed binding callback task , It is also the reason for the emergence of micro tasks 
          setTimeout(() => {
              _onResolve(value)
          }, 0)
      }
      executor(this.resolve, this.reject);
  }
  let demo = new MyPomise((resolve, reject) => {
      resolve(200)
  })
  demo.then((data) => {
      console.log(data)
  })

(4)Promise.resolve(value): Returns a value parsed with a given value Promise object

Promise.resolve(value) The parameters of the method are divided into four cases :

-- The parameter is one Promise Instance of object , Go straight back to this example

--

The parameter is one thenable object ( With then Method ),Promise.resolve() What is returned is an execution then After method Promise object , And adopt the state after execution

let thenable = {    
   then: function(resolve, reject) {
        resolve(200)
    }
}
let p1 = Promise.resolve(thenable); //200, because p1 It's already fulfilled state , So directly then, You can get the return value 
p1.then((data) => {
    console.log(data)
})

-- A parameter is a normal value or object , Then directly return the new Promise object , Status as fulfilled( The value is the parameter itself )

-- The parameter is empty. , Just return one fulfilled State of Promise object ,( The value is undefined)

(5) Chain call ,

then Callback function executed successfully , Back to a fulfilled State of promise, Will go into the back then

then Execution failure , Back to a rejected Of promise, Will go into the back catch

catch Callback function executed successfully , It's also a fulfilled State of promise, Into the back of then

catch Execution failure , Back to a rejected Of promise, Into the back of catch

  1. async/await
  • async/await The reason for this :undefinedPromise The programming model of adopts chain callback mode , Full of then function , There are defects in semantics
  • async/await Principle :
  • Used Promise
  • stay Promise Basic fit generator functions and coroutines , Asynchronous callbacks are implemented in the style of synchronous code programming
async function foo() {
    console.log(1);
    let a = await 100; // await The following code is equivalent to then Code in function 
    console.log(a);
    console.log(2);
}
console.log(0);
foo();
console.log(3);
// Execution order :0,1,3,100,2

async Function implementation principle .png

Generator function : Is a function with an asterisk , The execution can be suspended and resumed

actuator : Functions that execute generator functions , It becomes an actuator

coroutines : It's a lighter existence than threads ,

  • There can be multiple coroutines on a thread , But only one co process can be executed at the same time , Therefore, it is necessary to switch between processes
  • If from A Start the process B coroutines , We will take A The process is called B The father of Xie Cheng
function* genDemo() {
    console.log(" Start the first paragraph ");
    yield 'generator 1';//  encounter yield  keyword ,JavaScript  The engine pauses the execution of the function , And return the content after the keyword to the outside , External functions can be done by next() Resume to carry on 
    console.log(" Start the second paragraph ");
    yield 'generator 2;
 }
console.log('main 0')
let gen = genDemo(); // Created a gen coroutines , But it didn't execute 
console.log(gen.next().value) ; //generator 1
console.log('main 1')
console.log(gen.next().value); //generator 2
console.log('main 2')
2. Event cycle mechanism

Reference documents https://www.jianshu.com/p/12b9f73c5a4f/, This should be explained in more detail

Understanding the concept of stack (3 Kind of ):

  • The running environment of a piece of code , Last in, first out ( Execution context stack )
  • An area of memory in which data is stored , Stack space 、 Heap space undefined Stack space is structured , Each block is stored in a certain order undefined Heap space has no structure , Data can be stored at will .undefined The addressing speed of stack space is faster than that of heap space
  • Executable code execution mode , Execution stack ( The call stack ), fifo

Event loop execution process

    setTimeout(function () {
        console.log('timeout1');
    },0)
    new Promise(function (resolve) {
        console.log('promise1');
        resolve(100)
    }).then(() => {
        console.log('then1');
    })
    new Promise(function (resolve) {
        console.log('promise2');
        resolve(200)
    }).then(() => {
        console.log('then2');
    })
    setTimeout(function () {
        console.log('timeout2');
    },0)
    console.log('global1');
  1. First step , Start execution Javascript Script , Enter the macro task queue , Because there's only one script( The overall code ) Mission , Go straight to execution
  2. The second step , encounter setTimeout,setTimeout For a macro task , Asynchronous processing , Wait for the right time (100ms after ),timeout1 Join the macro task queue
  3. The third step , encounter Promise,Promise It's a synchronous task ,promise1, resolve(100), Put it on the execution stack immediately ( Execute in order ),undefinedthen Is the callback asynchronous function , Asynchronous processing , After processing ,then1 Join the micro task queue ( The time when the asynchronous task execution is added to the micro task team is the time sequence when the asynchronous task processing is completed , Not up and down in the code )
  4. Fourth parts , Meet the second Promise,promise2, resolve(200), Join the execution stack now ,undefinedthen2 Join the micro task queue
  5. Step five , Meet the second setTimeout,timeout2 Join the macro task queue
  6. thus , Call stack is empty ,Javascript All the synchronization task functions in the macro task have been executed

The execution stack when the synchronization task is completed .png

  1. Step six , Then go to the micro task queue to view the executable micro tasks ,then1 Add execution stack to execute , Execution completed , The execution stack is empty , Then go to the micro task queue to view the executable micro tasks , Add execution stack to execute , Go back and forth , Until the micro task queue is empty
  2. Part seven , View the macro task queue to execute macro tasks ,timeout2 The execution completion time is earlier than timeout, Therefore, first enter the execution stack to execute , Go back and forth , Until the macro task queue is empty
  3. All the tasks have been executed , Call stack is empty

Four 、 Page in browser

The life cycle of a page :

  • Loading phase
  • Update phase ( Interaction phase )
  • Destruction phase
( One ) Page optimization :

Think about the life cycle of the page :

1. Loading phase : How to make the page render faster ?

Key resources ( Core resources ): The resources that block the first rendering of a page are called the key resources of the page ,HTML、CSS、Javascript

  • Reduce the number of critical resources , Reduce requests
  • Reduce critical resource size , Improve resource loading speed
  • How many are needed to transfer key resources RTT(Round Trip Time)undefined--TCP When the protocol transmits resources , It is to divide resources into data packets ( It's usually 14KB about ), Multiple transfers back and forth undefined--RTT , It means that the client starts sending data , The time between receiving the confirmation message from the server

Specific optimization methods

(1) Compress HTML file , remove Unnecessary comments

(2) Merge and compress CSS 、JavaScript Wait for the documents ,script Tag plus async or defer attribute

(3) Avoid using table Layout

(4) cache ( When the second request hits the cache, the cache is read directly )

2. Update phase ( Interaction phase ): adopt Javascript operation DOM when , How fast the page will render again ?

The goal is to reduce the rearrangement of the page rendering process 、 Repaint

Specific optimization methods

(1) Reduce DOM operation , Will operate more than once DOM Merge into one , Such as inserting element nodes

(2) Reduce change style item by item , Best one time change style, Or define a style as class And one time update

(3) The front frame Vue、React( fictitious DOM and Diff Algorithm etc. )

(3) Avoid multiple reads offset Equal attribute , Use variables for caching

(4) Shake proof 、 throttle

(5) When making animation effects , Use will-change and transform Make optimization

( Two ) fictitious DOM And algorithms
  1. many times
1. Page loading phase :
  • On first load , First create a virtual DOM Trees ,
  • Then according to the virtual DOM Trees create real DOM Trees , Then continue a series of rendering pipeline work
2. Page loading phase :
  • If the data changes , Create a new virtual tree DOM Trees
  • Two virtual trees DOM Tree comparison , Calculate the minimum change
  • Update all the change records to the real one time DOM on the tree , Then continue a series of rendering pipeline work

Introduce virtual DOM Tree execution process .png

5、 ... and 、 Security in browser

The same-origin policy : agreement 、 domain name 、 If all three ports are the same, it is called homology
1. XSS attack : Cross-site scripting attacks (Cross Site Scripting)

XSS Attack means that hackers go to HTML In the file or DOM Inject malice into JavaScript Script , A means by which a user carries out an attack while browsing a page

(1) risk :
  • Stealing users Cookie Information undefined-- adopt document.cookie Get users Cookie Information , Send to malicious server undefined-- The malicious server gets the user's Cookie After the message , You can simulate a user's login , Transfer and other operations
  • Monitor user behavior undefined-- adopt addEventListener To listen for keyboard events , Get user account 、 password 、 Credit card and other information , Send to malicious server undefined-- Malicious servers get this information , And you can do a lot of illegal things
  • Generating advertisements and so on will affect the user experience
(2) resolvent :
  1. Filter or transcode the input script
 Such as :<script> -->&lt;script&gt;
  1. Response head Set-Cookie Add restrictions on use undefined-- httpOnly, Notify the browser of this Cookie Only through browser HTTP Protocol transfer , Browser's JS The engine will be disabled document.cookie;undefined-- SameSite=Strict, Limit this Cookie Cannot be sent across sites with jump links
2. CSRF attack , Cross-site request forgery (Cross Site Request Forgery)

The purpose is to exploit the vulnerability of the server and the login status of the user to carry out attacks

launch CSRF Mode of attack :

  • adopt <img src=" Malicious websites ">, Automatically jump to malicious websites
  • By inducing users to click on Hidden Links , Point to malicious websites

resolvent :

-- SameSite=Strict, Limit this Cookie Cannot be sent across sites with jump links

-- Verify the source site of the request

-- Use Token verification

The first time the server returns, it generates a Token

Again, request the client to bring the corresponding Token, To verify

原网站

版权声明
本文为[Great inventor]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112211406566948.html