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

04-05 1334阅读 0评论

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

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

拦截操作 

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

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

拦截请求代码放在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: [''] },
    ['requestBody']
)

 拦截到的post请求详情是:

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

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

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

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

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

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

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

解决中文乱码

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

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

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

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

 总的代码在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: [''] },
    ['requestBody']
)

免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,1334人围观)

还没有评论,来说两句吧...

目录[+]