Chrome扩展程序-使用不受信任的来源创建图像时出现JavaScript错误

ffscu2ro  于 2023-06-03  发布在  Go
关注(0)|答案(1)|浏览(197)

在我的chrome扩展中,我抓取了一些页面,然后稍后呈现结果。我觉得把favicons包括进来会很好。
事实证明,渲染我的索引中的一个favicon(还没有跟踪到一个)会导致这个错误:

Refused to load the script 'https://gohugo.io/dist/app.bundle.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

我可以想象有人在他们的hacked together hugo博客的favicon链接中指定一个js url;这一点并不神秘而且,很明显,我应该在抓取时间过滤掉非图像。但是,我对这个错误可能首先被抛出的事实感到困惑。我必须渲染favicons的代码是:

try {
                const resultImg = document.createElement("img");
                resultImg.src = result.favicon;
                if (result.favicon.includes(".js")) {
                    // this never hits
                    console.warn("found favicon that is js!");
                    console.dir(result);
                }
                resultImg.width = 24;
                resultImg.height = 24;
                resultImg.className = "favicon";
                return resultImg
            } catch (err) {
                return document.createElement("span")
            }

我非常确定这是导致错误的代码,因为注解掉它、重新加载和重新执行搜索是没有错误的,而取消注解、重新加载和重新执行搜索总是会导致错误。
这里的捕获是一个hail-mary,事实上它从来没有击中。我可能会将某种类型的加载侦听器附加到这个元素上,以防止出现错误。但究竟是什么原因导致chrome试图从图像标签的src加载脚本呢?
一个可能的线索是,当我试图在Chrome中加载https://gohugo.io/favicon-32x32.png时,它实际上加载了一个显示图像的小HTML页面。我没有看到hugo的html源代码中包含js,但也许有一些其他的favicon url在其神奇的html中包含了js包。另一方面,Curl只是在该路径上下载一个png。

mqxuamgl

mqxuamgl1#

此站点的服务器错误地添加了预加载该js文件的link头。由于CSP限制,它无法在扩展中运行,这就是显示错误的原因。
抑制该错误的唯一方法是添加declarativeNetRequest规则,以剥离由扩展发起的请求的标头:
//manifest.json

"minimum_chrome_version": "101",
  "permissions": ["declarativeNetRequestWithHostAccess"],
  "host_permissions": ["*://*.example.com/"],

//background.js

chrome.runtime.onInstalled.addListener(() => {
  const RULE = {
    id: 1,
    condition: {
      initiatorDomains: [chrome.runtime.id],
      resourceTypes: ['image'],
    },
    action: {
      type: 'modifyHeaders',
      responseHeaders: [
        {header: 'Link', operation: 'remove'},
      ],
    },
  };
  chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: [RULE.id],
    addRules: [RULE],
  });
});

相关问题