全域性攔截各種http請求
阿新 • • 發佈:2018-11-19
http請求無非就是ajax、src、href、表單
function hookAJAX() { XMLHttpRequest.prototype.nativeOpen = XMLHttpRequest.prototype.open; var customizeOpen = function (method, url, async, user, password) { // do something this.nativeOpen(method, url, async, user, password); }; XMLHttpRequest.prototype.open= customizeOpen; } /** *全域性攔截Image的圖片請求新增token * */ function hookImg() { const property = Object.getOwnPropertyDescriptor(Image.prototype, 'src'); const nativeSet = property.set; function customiseSrcSet(url) { // do something nativeSet.call(this, url); } Object.defineProperty(Image.prototype,'src', { set: customiseSrcSet, }); } /** * 攔截全域性open的url新增token * */ function hookOpen() { const nativeOpen = window.open; window.open = function (url) { // do something nativeOpen.call(this, url); }; } function hookFetch() { var fet = Object.getOwnPropertyDescriptor(window, 'fetch') Object.defineProperty(window,'fetch', { value: function (a, b, c) { // do something return fet.value.apply(this, args) } }) }