Chrome扩展程序,请在浏览器显示它之前,在响应码中替换HTML [英] Chrome extension, replace HTML in response code before browser displays it

查看:164
本文介绍了Chrome扩展程序,请在浏览器显示它之前,在响应码中替换HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有某种方式可以做这样的事情:
如果我在特定的网站上,我想要一些JavaScript文件直接从我的电脑加载(fe file:/// c:/ test.js),而不是来自服务器。



为此,我一直在考虑是否有可能制作扩展程序,以便在显示浏览器之前就可以更改HTML代码。所以整个过程应该如下所示:


  1. 请求

  2. 浏览器从服务器获取响应

  3. #响应已更改# - 这是扩展进入时的部分

  4. 浏览器解析更改后的响应并显示带有新响应的页面。 >

无论如何,它甚至不一定是Chrome扩展程序。它应该只是做上面描述的工作。它可以阻止原始文件并为另一个(DNS /代理?)服务,或者在我的计算机中过滤整个HTTP流量,并将特定的代码替换为另一个匹配的响应。 解决方案

您可以使用 WebRequest API 来实现该目标。例如,您可以添加 onBeforeRequest 侦听器并重定向一些请求:

  chrome.webRequest.onBeforeRequest.addListener(function(details)
{
var responseData =< div>一些文本< / div>
return {redirectUrl:data:text / html,+ encodeURIComponent(responseData)};
},{url:[https://www.google.com/]},[blocking]);

这将显示< div> 元素与文字一些文字,而不是谷歌的主页。请注意,您只能重定向到允许Web服务器本身重定向到的URL。这意味着重定向到 file:/// URLs是不可能的,并且只有在您的扩展名为无障碍网页 data: http:网址可以正常使用。


i wonder if there is some way to do something like that: If im on a specific site i want that some of javascript files to be loaded directly from my computer (f.e. file:///c:/test.js), not from the server.

For that i was thinking if there is a possibility to make an extension which could change HTML code in a response which browser gets right before displaying it. So whole process should look like that:

  1. request is made
  2. browser gets response from server
  3. #response is changed# - this is the part when extension comes in
  4. browser parse changed response and display page with that new response.

It doesnt even have to be a Chrome extension anyway. It should just do the job described above. It can block original file and serve another one (DNS/proxy?) or filter whole HTTP traffic in my computer and replace specific code to another one of matched response.

解决方案

You can use the WebRequest API to achieve that. For example, you can add a onBeforeRequest listener and redirect some requests:

chrome.webRequest.onBeforeRequest.addListener(function(details)
{
  var responseData = "<div>Some text</div>"
  return {redirectUrl: "data:text/html," + encodeURIComponent(responseData)};
}, {urls: ["https://www.google.com/"]}, ["blocking"]);

This will display a <div> element with the text "some text" instead of the Google homepage. Note that you can only redirect to URLs that the web server itself is allowed to redirect to. This means that redirecting to file:/// URLs is not possible, and you can only redirect to files inside your extension if these are web accessible. data: and http: URLs work fine however.

这篇关于Chrome扩展程序,请在浏览器显示它之前,在响应码中替换HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆