JS를 통해 글로벌 Ajax 요청 인스턴스 구문 분석을 가로채기

高洛峰
풀어 주다: 2017-03-28 14:39:00
원래의
2454명이 탐색했습니다.

다음과 같은 요구 사항이 있었던 적이 있습니까? 모든 Ajax 요청에 통합 서명을 추가해야 함, 특정 인터페이스가 요청된 횟수를 계산해야 함, 가져오거나 게시할 http 요청 방법을 제한해야 함, 다른 사람의 네트워크 프로토콜 등을 분석합니다. 그렇다면 어떻게 할까요? 생각해 보세요. 모든 Ajax 요청을 가로챌 수 있다면 문제는 매우 간단해질 것입니다!

Ajax-hook 소스코드 주소 : https://github.com/wendux/Ajax-hook

사용방법

1. ajaxhook.js를 소개합니다

<script src="wendu.ajaxhook.js"></script>
로그인 후 복사

2. 필요한 ajax 콜백이나 함수를 차단합니다.

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])
}
})
로그인 후 복사

좋아요, jQuery(v3.1)의 get 메소드를 사용하여 테스트합니다:

// get current page source code 
$.get().done(function(d){
console.log(d.substr(0,30)+"...")
})
로그인 후 복사

결과:

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

차단 성공! 또한 jQuery3.1이 onreadystatechange를 포기하고 대신 onload를 사용한 것을 볼 수 있습니다.

API

hookAjax(ob)

1.ob, 유형은 객체, 키는 필요 콜백 또는 함수에서 값은 차단 함수입니다.

2. 반환 값: 원본 XMLHttpRequest. 쓰기 요청이 있는데 가로채기를 원하지 않는 경우 new this를 사용할 수 있습니다.

unHookAjax()

1. 로드 차단, 제거 후에는 차단이 무효화됩니다.

Ajax 동작 변경

모든 Ajax 요청을 가로채고 요청 방법을 감지하고 "GET"인 경우 요청을 중단하고 프롬프트를 표시합니다

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

모두 가로채기 ajax 요청, 타임스탬프를 균일하게 추가하도록 요청

hookAjax({
open:function(arg){
arg[1]+="?timestamp="+Date.now();
} 
})
로그인 후 복사

"responseText" 요청에서 반환된 데이터 수정

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

결과:

hook!<!DOCTYPE html>
<html>
<h...
로그인 후 복사

다음 예를 사용하세요. , 나는 그것이 시작될 것이라고 믿습니다. 언급된 요구 사항은 쉽게 달성할 수 있습니다. 마지막으로 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
로그인 후 복사

참고

1. 부울, true인 경우 ajax 요청이 차단됩니다. 기본값은 false이며 요청이 차단되지 않습니다.

2. 모든 콜백 차단 함수의 매개변수는 onreadystatechange, onload와 같은 현재 XMLHttpRequest 인스턴스입니다. ajax 원래 메소드의 모든 차단 함수는 원래 매개변수를 다음 형식으로 차단 함수에 전달합니다. 이는 차단 기능에서 수정할 수 있습니다.

위는 편집자가 소개한 JS 가로채기 글로벌 Ajax 요청 예시 분석입니다. 궁금한 사항이 있으면 메시지를 남겨주시면 편집자가 답변해 드리겠습니다. 당신에게.

관련 기사:

인셉터에 의한 Ajax 요청 차단 인스턴스에 대한 자세한 설명

Node.js 서버 환경에서 Mock.js 사용 AJAX 요청 차단 튜토리얼

PHP를 통해 Ajax 요청인지 확인하는 방법

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!