Let’s talk about the cross-domain pitfalls that you need to use html2canvas to take project screenshots when doing projects.
The project needs to pull the user's avatar, and the avatars of LinkedIn and WeChat are stored in CDN, which involves cross-domain issues.
Pit 1:
Due to cross-domain, the canvas is polluted and the toBlob(), toDataURL() or getImageData() methods cannot be called. Calling them will throw a security error.
Do as told online.
Configure useCORS: true,
Nginx adds request header
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials: true;
Successfully solved the problem of canvas contamination. However, this solution can only solve the problem of your own server. You can't go to WeChat or other third-party servers to add request headers. . . A bigger pit is coming
Pit 2:
The image request was rejected by the other party's server.
Access to Image 'https://media.licdn.com/dms/image/C5603AQHCky1Ku581hg/profile-displayphoto-shrink_100_100/0?e=1573689600&v=beta&t=8TqbDk8iWCXXXXXXXXXXXXXXXXXXXXX' has been blocked from origin '127.0.0.1:8000'
Tried various approaches including
Add cross origin = "anonymous" to the img tag ;
Front-end page settings <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />;
Nginx set add_header Cache-Control no-store;
None were successful.
In the end, it was solved by Nginx, which was divided into two steps.
first step:
First, add the third-party cdn link saved by the server
‘https://media.licdn.com/dms/image/C5603AQHCky1Ku581hg/profile-displayphoto-shrink_100_100/0?e=1573689600&v=beta&t=8TqbDk8iWCXXXXXXXXXXXXXXXXXXXXX’
Save as:
"Region name/third_image /dms/image/C5603AQHCky1Ku581hg/profile-displayphoto-shrink_100_100/0?e=1573689600&v=beta&t=8TqbDk8iWC XXXXXXXXXXXXXXXXXXXXX"
Accessing a third-party domain name involves cross-domain, but accessing other local resource folders is OK.
Part Two:
Then set up the proxy on Nginx
location ^~ /third_image/ {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified- Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
proxy_pass https://media.licdn.com/;
}
That is:
Save https://media.licdn.com/dms/image/C5603AQHCky1Ku581hg/profile-displayphoto-shrink_100_100/0?e=1573689600&v=beta&t=8TqbDk8iWC XXXXXXXXXXXXXXXXXXXXX
as https://local domain name/third_image/dms/image/C5603AQHCky1Ku5 81hg/ profile-displayphoto-shrink_100_100/0?e=1573689600&v=beta&t=8TqbDk8iWC XXXXXXXXXXXXXXXXXXXXX
Finally, it is represented by Nginx as https://media.licdn.com/dms/image/C5603AQHCky1Ku581hg/profile-displayphoto-shrink_100_100/0?e=1573689600&v=beta&t=8TqbDk8iWC XXXXXXXXXXXXXXXXXXXXX
Perfect solution! I'm about to shed tears, it's so touching