【问题标题】:Chrome Extension - open tab without imagesChrome 扩展程序 - 打开没有图像的选项卡
【发布时间】:2018-08-17 08:48:20
【问题描述】:

我已经构建了一个 Chrome 扩展程序,可以在新选项卡中打开用于 html 解析的 url。一切正常,但我想通过在页面加载之前剥离图像来优化加载速度。

到目前为止,我是这样称呼标签的:

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
        }
      }
    }
  }
}

当调用 executeScript 时,已经太晚了,页面就在那里。有没有办法在页面加载之前执行脚本,以便我可以在获取 html 之前删除图像?

谢谢 洛朗

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    您可以将 chrome.webRequest API (https://developer.chrome.com/extensions/webRequest) 与 onBeforeRequest 一起使用 当请求即将发生时触发。此事件在建立任何 TCP 连接之前发送,可用于取消或重定向请求。这样的事情应该会阻止 .jpg 图像加载:

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

    【讨论】:

    • 最好提供像urls: '*://*/*.jpg'types: ['image']tabId: yourActualTabId这样的URL模式,以避免在其他URL上触发监听器。
    • 感谢你们!我想过使用正则表达式来捕获所有图像类型,但它似乎不起作用,我尝试了这个:“://*/.(jpg|gif)”。无论扩展名如何,有没有办法阻止所有图像?谢谢
    【解决方案2】:

    也许有人还需要这个。

    来自 chrome 文档:Chrome's Examples of webRequest Blocking

    您可以使用一个侦听器阻止多种类型的图像。

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

    您可以根据需要修改 URL 模式。

    不要忘记在您的manifest.json 文件中添加webRequestwebRequestBlocking 权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 2016-11-04
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2015-07-04
      • 2017-10-23
      • 1970-01-01
      相关资源
      最近更新 更多