問題描述
我想創建一個使用 webview 來顯示第 3 方內容的 Electron 應用.
I want to create an Electron app that will use webview to display 3rd party content.
我希望能夠攔截來自此 web 視圖的所有請求和響應.有時我想操縱這些內容,有時我想記錄它,有時我什么都不做.
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.
作為響應的一個示例,也許 Web 服務器會使用 TypeScript 代碼進行響應,也許我想獲取該響應,并將其編譯為標準 JavaScript.
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.
我查看了 此頁面,但看起來只能取消請求和操作標頭.WebRequest API 看起來不適合我的用例的需求,因為它只允許對請求和響應的操作非常細微.
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.
我也考慮過設置一些可以充當代理的網絡服務器,但我對此感到擔憂.我想維護用戶隱私,并且我想確保托管第 3 方內容的 Web 服務器看起來請求來自類似瀏覽器的環境(例如 Electron webview)而不是服務器.我知道我可以使用我發送的標頭等操作請求,但是整個解決方案變得更加復雜,然后我想,但可能是唯一的選擇.
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.
有沒有更好的方法來實現這一點,并且可以更好地控制 Electron webview?
Any better ways to achieve this, and have more control over the Electron webview?
推薦答案
我認為你應該研究一下協議API.它在內部充當代理.假設您希望用戶打開 http://www.google.com
并查看像 youve been conned!
這樣的內容.
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
});
與 WebRequest API 相比,還有很多工作要做.但它比獨立的本地代理要簡單得多.
there's lots of work to do, comparing to the WebRequest API. but it's much simpler than a independent local proxy.
這篇關于電子操縱/攔截 WebView 請求和響應的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!