• home > webfront > browser > Puppeteer >

    Puppeteer 调试线上页面:拦截请求替换本地文件debugger

    Author:zhoulujun Date:

    由于 Puppeteer 可以在请求发出前进行拦截与替换,所以很方便地在本地开发解决线上Bug以及新需求。这样可以减少无谓的提交同时真实地检验

    由于 Puppeteer 可以在请求发出前进行拦截与替换,所以很方便地在本地开发解决线上Bug以及新需求。这样可以减少无谓的提交同时真实地检验其在线上环境中的效果。

    setRequestInterception

    开启拦截:page.setRequestInterception(true) 

    官方文档:https://pptr.dev/api/puppeteer.page.setrequestinterception/

    注意:启用了拦截,那么就会自动开启无缓存状态。

    拦截器案例

    https://pptr.dev/guides/network-interception

    拦截ajax请求

    const page = await browser.newPage();
    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();
      }
    });

    根据url拦截

    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();
      }
    });

    据此,我们可以替换百度首页的css

    const puppeteer = require('puppeteer')
    const fs = require('fs')
    const util = require('util')
    const readFile = util.promisify(fs.readFile)
    
    (async function start() {
      const browser = await puppeteer.launch({
        args: ['--disable-infobars''--no-sandbox''--disable-setuid-sandbox'],
        // 因为我们需要直接看到UI效果,所以这里不能使用headless模式
        headlessfalse,
        // 也可以直接使用本地Chrome查看效果,不使用Puppeteer自带的Chromium浏览器
        //executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
      })
      let page = await browser.newPage()
      // 读写本地的CSS文件
      let customResponse = await readFile('./soutu.css')
      try {
        await page.setViewport({width1280height620})
        // 设置拦截请求
        await page.setRequestInterception(true)
        page.on('request'req => {
          let addr = req.url()
          // 根据URL拦截,这里拦截所有以CSS结尾的文件,可以自由修改
          if (addr.endsWith('css')) {
            req.respond({
              status200,
              contentType'text/css',
              body: customResponse



    参考文章:

    Puppeteer 调试线上页面 https://ifun.dev/post/puppeteer-online-debug/




    转载本站文章《Puppeteer 调试线上页面:拦截请求替换本地文件debugger》,
    请注明出处:https://www.zhoulujun.cn/html/webfront/browser/Puppeteer/9433.html

    TOP