Home  >  Article  >  Web Front-end  >  Js intercepts global ajax request

Js intercepts global ajax request

小云云
小云云Original
2017-12-09 16:52:431743browse

Have you ever had the following needs: need to add a unified signature to all ajax requests, need to count the number of times a certain interface is requested, need to limit the method of http requests to get or post, need to analyze other people's network protocols Wait, so how? Think about it, if you can intercept all ajax requests, then the problem will become very simple!


How to use

1. Directly introduce the script

  1. Introduce ajaxhook.js

    <script src="wendu.ajaxhook.js"></script>
  2. Intercept the required ajax callback or function.

    hookAjax({
        //拦截回调
        onreadystatechange:function(xhr){
            console.log("onreadystatechange called: %O",xhr)
        },
        onload:function(xhr){
            console.log("onload called: %O",xhr)
        },
        //拦截函数
        open:function(arg){
         console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])
        }
    })

ok, we use the get method of jQuery (v3.1) to test:

// get current page source code 
$.get().done(function(d){
    console.log(d.substr(0,30)+"...")
})

Result:

> open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true
> onload called: XMLHttpRequest
> <!DOCTYPE html>
  <html>
  <head l...

The interception was successful! We can also see that jQuery3.1 has abandoned onreadystatechange and used onload instead.

2. In the module building tool environment under CommonJs

Assuming that it is under webpack, the first step is to install the ajax-hook npm plug-in

npm install ajax-hook --save-dev

The second step is to introduce the module And call the api:

const ah=require("ajax-hook")
ah.hookAjax({ 
  onreadystatechange:function(xhr){ ... },
  onload:function(xhr){ ... }, 
  ...
})
...
ah.unHookAjax()

API

hookAjax(ob)

  • ob, the type is an object, and the key is the callback or function you want to intercept. value is our interception function.

  • Return value: Original XMLHttpRequest. If you have a write request and don't want to be intercepted, you can use new this.

unHookAjax()

  • Uninstall interception; after uninstallation, interception will be invalid.

Change ajax behavior

Intercept all ajax requests, detect the request method, if it is "GET", interrupt the request and give a prompt

hookAjax({
  open:function(arg){
    if(arg[0]=="GET"){
      console.log("Request was aborted! method must be post! ")
      return true;
    }
  } 
 })

Intercept all ajax requests and add timestamps to the requests

hookAjax({
  open:function(arg){
    arg[1]+="?timestamp="+Date.now();
  } 
 })

Modify the data "responseText" returned by the request

hookAjax({
   onload:function(xhr){
    //请求到的数据首部添加"hook!" 
    xhr.responseText="hook!"+xhr.responseText;
   }
 })

Result:

hook!<!DOCTYPE html>
<html>
<h...

With these examples, I believe it was mentioned at the beginning requirements are easily fulfilled. Finally, test the output of unHook

   hookAjax({
        onreadystatechange:function(xhr){
            console.log("onreadystatechange called: %O",xhr)
            //return true

        },
        onload:function(xhr){
            console.log("onload called")
            xhr.responseText="hook"+xhr.responseText;
            //return true;
        },
        open:function(arg){
          console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])
          arg[1]+="?hook_tag=1";

        },
        send:function(arg){
         console.log("send called: %O",arg[0])
        }
    })

    $.get().done(function(d){
        console.log(d.substr(0,30)+"...")
        //use original XMLHttpRequest
        console.log("unhook")
        unHookAjax()
        $.get().done(function(d){
            console.log(d.substr(0,10))
        })

    })

:

open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true
send called: null
onload called
hook<!DOCTYPE html>
<html>
<he...
unhook
<!DOCTYPE

Note

  1. The return value of the interception function is a boolean. If it is true, the ajax request will be blocked. , the default is false, and the request will not be blocked.

  2. The parameters of all callback interception functions are the current XMLHttpRequest instance, such as onreadystatechange, onload; all interception functions of the ajax original method will pass the original parameters to the interception function in the form of an array, You can modify this in the interceptor function.

Related recommendations:

Solution to the interception of window.open() in opening a new window after the ajax request is successful

ajax callback to open a new form to prevent the browser from intercepting effective methods

About using JavaScript to intercept the form's submit method implementation

The above is the detailed content of Js intercepts global ajax request. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn