【问题标题】:Using WebP fallback with CSP将 WebP 回退与 CSP 结合使用
【发布时间】:2021-07-24 03:33:22
【问题描述】:

我正在使用以下内容来使用带有 JPG 后备的 WebP 图像:

<img 
    src="{{ $img_webp_desktop.RelPermalink }}" 
    onerror="this.onerror=null;this.src='{{ $img_jpg_desktop.RelPermalink }}';" 
    loading="lazy"
    height="{{ $img_jpg_desktop.Height }}" 
    width="{{ $img_jpg_desktop.Width }}">

但是,当我的 CSP 设置为 script-src 'self' 时,onerror 内联脚本不会被执行并且回退不起作用。

有什么方法可以让 CSP 工作?最坏的情况,我可以启用unsafe-hashes

提前致谢:)

【问题讨论】:

    标签: html content-security-policy hugo


    【解决方案1】:

    您可以像这样使用data-... 属性:

    <img 
        src="{{ $img_webp_desktop.RelPermalink }}" 
        data-src="{{ $img_jpg_desktop.RelPermalink }}" 
        loading="lazy"
        height="{{ $img_jpg_desktop.Height }}" 
        width="{{ $img_jpg_desktop.Width }}">
    

    然后将onerror 事件侦听器普遍添加到所有具有 data-src 属性的图像:

    imgList = document.querySelectorAll("img[data-src]");
    imgList.forEach( function(img) {
      img.addEventListener( 'error', function(e) {
        e.target.removeEventListener(e.type, arguments.callee);
        e.target.src = e.target.getAttribute("data-src");
        });
      });
    

    最坏的情况,我可以启用'unsafe-hashes'

    是的,这真的很糟糕。 Safari 不支持'unsafe-hashes'。很难管理很多'hash-values',所有onerror 都会有一个独特的。更改图像名称后,您需要重新计算并替换哈希。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      相关资源
      最近更新 更多