捕获Webview的请求和响应 [英] Capture webview requests and responses

查看:668
本文介绍了捕获Webview的请求和响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用程序,用户可以在其中通过webview元素浏览网页.

I am creating an app in which the user can browse the web via a webview element.

<webview src='user-generated'></webview>

我希望能够捕获过程中生成的所有请求和响应.在过去的两个小时中,我一直在寻找解决方法,但没有发现任何与远程相关的东西.

I would like to be able to capture all of the requests and responses that are generated in the process. I have been looking around for the past two hours trying to figure out how to do this, but have not found anything even remotely relevant.

我阅读了一些有关使用session检索会话cookie的内容,并且我曾想过诸如请求和响应之类的其他内容,尽管它似乎并没有返回任何有用的信息.

I read something about using session to retrieve session cookies, and I had imagined other stuff like requests and responses, although it does not seem to return anything useful to this end.

webview.addEventListener('dom-ready', function(){
  console.log(remote.getCurrentWindow().webContents.session)
})

有什么方法可以捕获所有请求和响应,最好是使用webview?

Is there any way to capture all of the requests and responses, ideally with webview?

这是我到目前为止所获得的,尽管它返回的似乎是请求或响应,但我不确定是否来自Webview.明天我必须仔细看一下.

Here is what I got so far, and, although it is returning what seems to be requests or responses, I am not yet sure if it is from webview. I will have to take a closer look tomorrow.

ipcMain.on('asynchronous-message', (event, arg) => {
  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    event.reply('asynchronous-reply', details)
    callback({ requestHeaders: details.requestHeaders })
  })
})

渲染器

ipcRenderer.send('asynchronous-message', webview) // Should I be sending `webview` as the argument?
ipcRenderer.on('asynchronous-reply', (event, payload) => {
  console.log(paylod)
})

推荐答案

您可以在Webview会话上访问onBeforeSendHeaders.获取会话的最简单方法是设置webview分区.

You can access the onBeforeSendHeaders on the webview session. Easiest way to get the session is by setting the webview partition.

<webview src='user-generated' partition='my-webview-partition'></webview>

主要

var ses = session.fromPartition('my-webview-partition');
ses.webRequest.onBeforeRequestHeaders((details, callback) => {
  details.requestHeaders['User-Agent'] = 'MyAgent'
  callback({ requestHeaders: details.requestHeaders })
});

这篇关于捕获Webview的请求和响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆