简体   繁体   中英

Electron Manipulate/Intercept WebView Requests and Responses

I want to create an Electron app that will use webview to display 3rd party content.

I would like to be able to intercept all requests and responses from this webview. Sometimes I would like to manipulate this content, other times I would like to log it, and other times I'd like to do nothing.

As one example for the responses, maybe a web server will respond with TypeScript code, maybe I want to take that response, and compile it to standard JavaScript.

I have looked into this page but it looks like it is only possible to cancel requests, and manipulate the headers. The WebRequest API doesn't look to fit the needs of my use case since it only allows very minor manipulations of requests and responses.

I have also considered setting up some time of web server that can act as a proxy, but I have concerns about that. I want to maintain user privacy, and I want to ensure that to the web servers that host the 3rd party content it looks like the request is coming from a browser like environment (ex. Electron webview) instead of a server. I know I can manipulate requests with the headers I send and such, but this whole solution is getting to be a lot more complicated, then I would like, but might be the only option.

Any better ways to achieve this, and have more control over the Electron webview?

I think you should look into the Protocol API . It works as a proxy internally.

Say you want the user, when opening http://www.google.com , to see content like you've been conned! :

 const { protocol } = require("electron"); const content = new Buffer("you've been conned!"); protocol.interceptBufferProtocol("http", (request, result) => { if (request.url === "http://www.google.com") return result(content); ... // fetch other http protocol content and return to the electron });

There's lots of work to do, compared to the WebRequest API , but it's much simpler than an independent local proxy.

To get the request body of any http network call made by your electron app:

session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
        if (details.uploadData) {
            const buffer = Array.from(details.uploadData)[0].bytes;
            console.log('Request body: ', buffer.toString());
        }
        callback(details);
      })

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