【问题标题】:How can we use electron.protocol.interceptFileProtocol with only certain paths, leaving other requests untouched?我们如何才能只使用特定路径的 electron.protocol.interceptFileProtocol ,而不影响其他请求?
【发布时间】:2020-03-28 06:50:15
【问题描述】:

我想拦截某些 HTTP 请求并将它们替换为文件。所以我想我可以像这样使用electron.protocol.interceptFileProtocol

protocol.interceptFileProtocol('http', (request, callback) => {
  // intercept only requests to "http://example.com"
  if (request.url.startsWith("http://example.com")) {
    callback("/path/to/file")
  }

  // otherwise, let the HTTP request behave like normal.
  // But how?
})

我们如何允许http://example.com 以外的其他http 请求继续正常工作?

【问题讨论】:

  • 知道如何从webview 捕获请求/响应吗?我一直在这个问题上停留了一段时间。这是我的question

标签: javascript electron


【解决方案1】:

不确定是否有办法做到这一点?但我做了类似的事情是使用session.defaultSession.webRequest.onBeforeRequest 见:https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest

类似

session.defaultSession.webRequest.onBeforeRequest({urls: ['http://example.com']}, function(details, callback) {
  callback({
    redirectURL: 'file://' + this.getUrl(details.url)
  });
});

如果您需要的不仅仅是重定向,您可以重定向到您自己的自定义协议(例如,mycustomprotocol://... 之类的网址)。您可以使用protocol.registerStringProtocol 等实现自己的协议处理程序。

我在电子中分别使用了 onBeforeRequest 和 registerStringProtocol,到目前为止没有任何问题,但从来没有一起使用 - 尽管我猜想应该一起工作。

【讨论】:

  • 知道如何从webview 捕获请求/响应吗??我一直在这个问题上停留了一段时间。这是我的question
  • 这似乎因为某种原因而挂起。
  • 有效吗?因为我和这里有同样的问题:github.com/electron/electron/issues/12242你用的是什么电子版本?我在 5.0.13
  • 我一直在尝试使用文件协议和注册自定义协议,但它似乎不起作用。
【解决方案2】:

当使用protocol.interceptXXXXProtocol(scheme, handler)时,我们正在拦截方案协议,并使用handler作为协议的新handler,它发送一个新的XXXX请求作为响应,如in the doc here所说。

但是,这样做完全破坏了这个特定协议的初始处理程序,我们在处理回调执行后需要它。因此,我们只需要将它恢复到初始状态,它就可以继续正常工作:)

让我们使用:protocol.uninterceptProptocol(scheme)

protocol.interceptFileProtocol('http', (request, callback) => {
  // intercept only requests to "http://example.com"
  if (request.url.startsWith("http://example.com")) {
    callback("/path/to/file")
  }

  // otherwise, let the HTTP request behave like normal.
  protocol.uninterceptProtocol('http');
})

【讨论】:

  • 不错!很久没有答案了。
  • 我没有测试过这个。这与删除事件侦听器相同吗?描述说“删除为方案安装的拦截器并恢复其原始处理程序。”。如果我理解正确的话,我们第一次收到http 请求,不管它是否为example.com,处理程序都会被删除,然后我们将永远不会处理任何未来的请求。如果我的理解是正确的,那么这是行不通的。我们每次都需要处理example.com请求,否则每次都正常处理。
  • 你确实是对的。我想我们在这里缺少的是默认/原始处理程序的当前实现。如果我们可以访问它,那么我们可以通过在 if/else 条件块中使用它来覆盖它。
  • 那太好了!
猜你喜欢
  • 1970-01-01
  • 2020-12-06
  • 2016-11-16
  • 2018-10-10
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 2013-02-10
相关资源
最近更新 更多