简体   繁体   English

Chrome 扩展程序 - 打开没有图像的标签

[英]Chrome Extension - open tab without images

I have built a Chrome Extension that opens urls for html parsing in a new tab.我已经构建了一个 Chrome 扩展程序,可以在新选项卡中打开用于 html 解析的 url。 Everything works fine but I'd like to optimize the loading speed by stripping images before the page is loaded.一切正常,但我想通过在页面加载之前剥离图像来优化加载速度。

So far I call the tab this way:到目前为止,我这样称呼标签:

function CreateTab(createProperties, shop_list) {
  return new Promise((resolve, reject) => {
    chrome.tabs.create(createProperties, tab => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError));
      } else {
        chrome.tabs.executeScript(tab.id, {
          file: 'GetSource.js',
        }, async function(results) {
          my parsing code here
        }
      }
    }
  }
}

When executeScript is called, it's already too late, the page is there.当executeScript被调用时,已经太晚了,页面就在那里。 Is there a way to execute a script before the page is loaded so that I can remove images before getting the html ?有没有办法在页面加载之前执行脚本,以便我可以在获取 html 之前删除图像?

Thanks Laurent谢谢洛朗

You can use chrome.webRequest API ( https://developer.chrome.com/extensions/webRequest ) with onBeforeRequest which fires when a request is about to occur.您可以将chrome.webRequest API ( https://developer.chrome.com/extensions/webRequest ) 与onBeforeRequest一起使用,API 在请求即将发生时触发。 This event is sent before any TCP connection is made and can be used to cancel or redirect requests.此事件在建立任何 TCP 连接之前发送,可用于取消或重定向请求。 Something like this should prevent .jpg images from loading:像这样的事情应该阻止 .jpg 图像加载:

chrome.webRequest.onBeforeRequest.addListener(
        function(details) {
          return {cancel: details.url.indexOf(".jpg") != -1};
        },
        {urls: ["<all_urls>"]},
        ["blocking"]);

Maybe somebody still need this.也许有人还需要这个。

From the chrome documentation : Chrome's Examples of webRequest Blocking来自 chrome 文档: Chrome 的 WebRequest 阻塞示例

You can block multiple type of images using one listener.您可以使用一个侦听器阻止多种类型的图像。

chrome.webRequest.onBeforeRequest.addListener(
    function(details) { 
        return { cancel: true }; 
    },
    
    { 
        urls: ["*://*/*.jpg", "*://*/*.png", "*://*/*.gif", "*://*/*.ico"] 
    },
    
    ["blocking"]
);

You can modify the URL patterns as you need.您可以根据需要修改 URL 模式。

Don't forget to add webRequest and webRequestBlocking permissions in your manifest.json file.不要忘记在manifest.json文件中添加webRequestwebRequestBlocking权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM