Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - 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)
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...