Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
Charlie Fish Avatar asked Jun 21 '18 17:06

Charlie Fish


1 Answers

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.

like image 191
notXX Avatar answered Oct 05 '22 01:10

notXX