chrome插件webRequest拦截请求并获取post请求体requestBody数据raw内容,解决中文乱码问题

详细使用说明可以看官方文档:https://developer.chrome.com/docs/extensions/reference/api/webRequest?hl=zh-cn

拦截操作 

想要通过浏览器插件拦截请求的话,需要在manifest.json里面添加webRequet权限:

拦截请求代码放在background.js里面:(下面代码解析中文乱码

export {}

console.log(
    'Live now; make now always the most precious time. Now will never come again.'
)
// 监听发送请求
chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        console.log('请求详情', details)
        if (details.method == 'POST') {
            var postedString = decodeURIComponent(
                String.fromCharCode.apply(
                    null,
                    new Uint8Array(details.requestBody.raw[0].bytes)
                )
            )
            console.log('请求体内容', postedString)
        }
        return { cancel: false }
    },
    { urls: ['<all_urls>'] },
    ['requestBody']
)

 拦截到的post请求详情是:

可以看到requestBody内容是raw格式数据: 里面是bytes字节类型

想要看到原始内容,需要解析raw数据:(这种方式会中文乱码

        if (details.method == 'POST') {
            var postedString = decodeURIComponent(
                String.fromCharCode.apply(
                    null,
                    new Uint8Array(details.requestBody.raw[0].bytes)
                )
            )
            console.log('请求体内容', postedString)
        }

解析后的数据就是明文了: 

解决中文乱码

中文乱码主要出现是因为 String.fromCharCode.apply 引起的。想要解决中文乱码就要换一种解码方式,使用TextDecoder解码就可以了:

            const decoder = new TextDecoder('utf-8')
            var postedString = decoder.decode(
                new Uint8Array(details?.requestBody?.raw[0].bytes)
            )
            console.log('请求体内容', postedString)

可以看到中文正常显示了: 

 总的代码在background.js里面:

import { escape } from 'querystring'

export {}

console.log(
    'Live now; make now always the most precious time. Now will never come again.'
)
// 监听发送请求
chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        console.log('请求详情', details)
        if (details.method == 'POST') {
            const decoder = new TextDecoder('utf-8')
            var postedString = decoder.decode(
                new Uint8Array(details?.requestBody?.raw[0].bytes)
            )
            console.log('请求体内容', postedString)
        }
        return { cancel: false }
    },
    { urls: ['<all_urls>'] },
    ['requestBody']
)
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1024小神

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值