Electron Manipulate/Intercept WebView Requests and

2020-06-01 08:24发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2020-06-01 09:00

I think you should look into The Protocol API. it works as a proxy internally. say you wanna the user open http://www.google.com and 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, comparing to the WebRequest API. but it's much simpler than a independent local proxy.

查看更多
Fickle 薄情
3楼-- · 2020-06-01 09:25

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);
      })
查看更多
登录 后发表回答