html5中拦截url,puppeteer 拦截页面请求
注意:
監聽的請求的類型有: document,stylesheet,image,media,font,script,texttrack,xhr,fetch,eventsource,websocket,manifest,other
攔截請求需要開啟 await page.setRequestInterception(true);
await req.respond()和await req.continue() 不能同時調用
使用await req.respond() 攔截返回值注意跨域
使用await req.respond() 攔截返回值注意返回json或字符串
main.js
const pptr = require('puppeteer');
async function bootstrap() {
const browser = await pptr.launch({
headless: false,
slowMo: 250,
});
const page = await browser.newPage();
page.on('console', m => {
// console.log(m.text());
});
await page.setRequestInterception(true);
page.on('request', async req => {
if (req.resourceType() === 'xhr') {
console.log(req.url());
await req.respond({
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
},
contentType: 'application/json; charset=utf-8',
body: JSON.stringify({ code: 0, data: 'hello puppeteer' }),
});
// await req.continue();
} else {
await req.continue();
}
});
page.on('response', async res => {
if (res.url().indexOf('/header') >= 0) {
console.log(res.status());
// 原本接口返回的數據 {"code":0,"data":"hello ajanuw"}
console.log(await res.text());
// await browser.close();
}
});
page.on('requestfinished', req => {
console.log(`請求完成: ${req.url()}`);
});
page.on('requestfailed', req => {
console.log(`請求失敗: ${req.url()}`);
});
await page.goto('http://127.0.0.1:5500/index.html');
}
bootstrap();
index.html
Documentclick get
{{ data | json }}
const http = axios.create({
baseURL: 'http://127.0.0.1:5000',
});
new Vue({
el: '#app',
data() {
return {
data: ''
};
},
methods: {
get() {
http('/header').then(({ data }) => {
console.log(typeof data.data);
this.data = data
});
},
},
mounted() {},
});
接口
@Get('/header')
@Header('Access-Control-Allow-Origin', '*')
test() {
return {
code: 0,
data: 'hello ajanuw',
};
}
總結
以上是生活随笔為你收集整理的html5中拦截url,puppeteer 拦截页面请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: KiCad设计PCB-7-制作自锁开关K
- 下一篇: dicom格式文件讲解(一)