HTML2Canvas with CORS in S3 and CloudFront

2019-04-27 03:25发布

问题:

I have a problem and I'm totally desperate... :(

I'm using HTML2Canvas to create a screenshot of a div with many contents.

I have read many similar questions: Question 1 and Question2, and I have found another one very similar to my problem:

CORS policy on cached Image

In Firefox, all is working fine, but in Chrome, I'm having problems with the CORS. I have this error:

Image from origin 'http://files.domain.ly' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:58943' is therefore not allowed access.

I have configured the CORS on this way in my S3 Bucket:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>localhost</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>localhost:58943</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>files.domain.ly</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

The files.domain.ly is the CNAME of the CloudFront.

The HTML2Canvas code:

html2canvas(document.getElementById('zoom_container'), {
  useCORS: true
}).then(function (canvas) {
  canvas.id = "image_canvas_render";
  document.body.appendChild(canvas);
  var img = canvas.toDataURL();
  img.id = "image_render_canvas";
});

Why it's working on Firefox but not in Chrome or Safari?

The files in the S3 are public and I can access directly throught any web explorer without any problem.

I have tried with attribute crossorigin="anonymous" in img tag, but it's not working.

Thank you so much!!

Edited: Sometimes it's working, and sometimes no... cache problem?