Chrome 65阻挡了交叉起源的. Client-side workaround to force download?

问题描述 投票:16回答:2

Chrome 65删除了对具有交叉源downloads的锚元素的href属性的支持:

Block cross-origin <a download>

为了避免本质上是用户介导的跨源信息泄漏,Blink现在将忽略具有交叉原点属性的锚元素上的下载属性的存在。请注意,这适用于HTMLAnchorElement.download以及元素本身。

Intent to Remove | Chromestatus Tracker | Chromium Bug

这打破了serverless downloads(对于跨源资源)。 它还破坏了Reddit Enhancement Suite的保存图像按钮(.res-media-controls-download) RES v5.12.0 fixed this使用chrome.downloads API(扩展程序现在请求您的管理下载权限)

任何解决方法?

更多细节在Web spec,谢谢@jbmilgrom

javascript google-chrome frontend tampermonkey
2个回答
23
投票

根据discussion blob:data:网址不受影响,所以这里有一个使用fetch和Blobs的解决方法。

Client-side force download media

function forceDownload(blob, filename) {
  var a = document.createElement('a');
  a.download = filename;
  a.href = blob;
  // For Firefox https://stackoverflow.com/a/32226068
  document.body.appendChild(a);
  a.click();
  a.remove();
}

// Current blob size limit is around 500MB for browsers
function downloadResource(url, filename) {
  if (!filename) filename = url.split('\\').pop().split('/').pop();
  fetch(url, {
      headers: new Headers({
        'Origin': location.origin
      }),
      mode: 'cors'
    })
    .then(response => response.blob())
    .then(blob => {
      let blobUrl = window.URL.createObjectURL(blob);
      forceDownload(blobUrl, filename);
    })
    .catch(e => console.error(e));
}

downloadResource('https://giant.gfycat.com/RemoteBlandBlackrussianterrier.webm');

但是,fetch仅适用于某些URL。您可能会收到CORS错误:

Failed to load https://i.redd.it/l53mxu6n14o01.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://redditp.com' is therefore not allowed access.

有一些扩展可让您拦截,修改或删除网站的安全标头:

UnXSS - Chrome Web Store

(但是设置Access-Control-Allow-Origin: *为我打破了YouTube)

Performance

请注意,这种方法效率不高!有时我的下载速度<1分钟。在此期间,页面的其余部分都是响应式的。我没有调查过这个,但我想创建大型Blob是资源密集型的。

Violentmonkey / Tampermonkey

如果你的用例是userscripts,那就是GM_download(options), GM_download(url, name)

⚠在Tampermonkey中,这是一个测试版功能,您必须首先在Tampermonkey Dashboard> Settings中设置下载模式:[BrowserAPI▾]

Tampermonkey Dashboard > Settings > Downloads


2
投票

显然,web specification在某些方面改变了不允许跨源下载。在响应中添加content-disposition: attachment标头,并且跨源下载可能再次起作用。

© www.soinside.com 2019 - 2024. All rights reserved.