简体   繁体   中英

Capture webview requests and responses

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.

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

Is there any way to capture all of the requests and responses, ideally with 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.

main

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

renderer

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

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>

main

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM