Make sure to include crossorigin="anonymous" in all img tags before the images start loading

I am currently facing issues with my canvas displaying errors due to cached images causing CORS policy errors. The solution I am considering is adding

crossorigin="anonymous"
to all the images on my website. However, I am unsure of how to implement this before the images are loaded in order to ensure they are loaded with the appropriate headers that won't affect my canvas.

$('img').each(function() {
     var $img = $(this);
     $img.attr('crossorigin', anonymous);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img width="50%" src="https://ychef.files.bbci.co.uk/1600x900/p08ysrxd.webp">

Answer №1

To ensure your code works properly (after resolving syntax errors), it is essential to manage the crossOrigin attribute before reaching the next microtask checkpoint. This means that the setting must be done synchronously, not in an async script or event handler.

Although most browsers adhere to this rule, some may load cached images synchronously. To prevent this issue, you can simply reset the src to the same value, forcing the browser to load the resource with the correct headers.

$('img').each(function() {
  var $img = $(this);
  $img.attr({
    crossorigin: "anonymous",
    src: this.src
  });
});

// check if loaded with proper headers
$(window).on("load", () => {
  const canvas = document.createElement("canvas");
  canvas.getContext("2d").drawImage($('img')[0], 0, 0);
  console.log('cross-origin enabled', !!canvas.toDataURL());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img width="50%" src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png">

If I were in your position, I would double-check the timing for this action. The ideal solution is to set the attribute from the beginning:

// check if loaded with proper headers
window.onload = () => {
  const canvas = document.createElement("canvas");
  canvas.getContext("2d").drawImage( document.querySelector('img'), 0, 0);
  console.log('cross-origin enabled', !!canvas.toDataURL());
};
<img crossorigin="anonymous" width="50%" src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png">

It's worth noting that the image in question is served by Amazon S3 with a Vary: Origin header only for cross-origin requests. This setup causes Chrome to still use the cached version, even when the crossOrigin attribute is specified. For further details, refer to this Q/A thread.

In such scenarios, the best workaround is always setting the crossOrigin attribute.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``Are you looking to create multiple canvases in a loop?

I've managed to get this command working exactly as I wanted: http://jsfiddle.net/m1erickson/64BHx/ However, I didn't anticipate how challenging it would be to turn the drawing into reality here: What I attempted to do is illustrated in this li ...

Flickity remains in plain sight on desktop devices

I am trying to hide the flickity slider on desktop and larger devices. I have followed the instructions in the documentation, but for some reason, it's not working as expected. Here is how the div looks: <div class="w-full flex pl-4 pb-16 overflo ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

Is it possible to add animation to an SVG filter to create a captivating rotating planet with color effects?

I've added a filter to my self-created SVG and I'm interested in animating it so that the colors move diagonally, giving the appearance of a spinning planet. Below is the code featuring my SVG and how I'd like it to begin with the blue colo ...

Tips for customizing the appearance of Material UI's time picker diolog styles

I am currently incorporating the Material UI Time Picker from GitHub, specifically TeamWertarbyte's repository. My task involves modifying the color of the time displayed. In the image provided, I aim to customize the color of the time shown as 11:3 ...

What is the best way to retrieve a document element in React when utilizing an external script?

In my React project, I have successfully implemented a chat button using an external script. However, I encountered an issue where I needed to hide the chat button on specific pages. Since I couldn't access the button's element using a ref, I res ...

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

Centering an image that is absolutely positioned within a container that is relatively positioned, horizontally

Looking to center an image that is positioned absolutely horizontally within a container that is relatively positioned. After attempting with CSS and not finding success, I ended up using Jquery. http://jsfiddle.net/CY6TP/ [This is my attempt using Jquery ...

Only a fragment of the .attr() method

I am trying to work with an image HTML block <img src="folder1/folder2/folder3/logo1.png"> situated inside a large div similar to this structure <div id="editorial"> <div id="img_editorial"><img src="folder1/folder2/folder3/logo1. ...

Encountering an issue when trying to upload a file for the second time

I am currently working on a project where I need to upload an excel file and send it to an API using ReactJS. So far, I have been able to successfully send the file to the API. However, in my submit function, I want to reset the saved excel file from the s ...

Creating an array of form input names using JavaScript within the HTML input tag

I have a two part question that I'm hoping someone can help me with. There was a similar question asked recently that included information about this particular type of array in PHP, but unfortunately, I can't seem to locate it at the moment. 1. ...

Issue with regex replacement behaving differently in Node compared to console

I am having trouble properly escaping commas in a sentence. Oddly enough, my replace method is not functioning correctly in node, while it works fine in the Chrome console. Is there anyone who has a solution to this issue? It seems to be occurring with al ...

Hiding a div using swipe gestures in Angular

What am I trying to achieve? I aim to hide a div when swiped right. This specific action will close the pop-up that appears after clicking a button. What tools are at my disposal? I am utilizing Ionic framework for this task. Within my app.js, I have i ...

Activate the 'swipe back' feature within ion-item upon selecting ion-option-button

In my Ionic project, I created an ion-list with ion-items and added ion-option-buttons: <ion-list> <ion-item class="item " ng-repeat="exercise in exercises" on-double-tap="sendToChangeExercise"> <p><h2>{{exercise. ...

Switching perspective in express with Pug

Hello everyone, I'm still getting the hang of using Node.js with Express and Jade. I've successfully set up a basic 1 page app where a login page is displayed by default. Once the user logs in and is authenticated against a database, the function ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

Issues with Salesforce OAuth redirect CORS in Express Node application

I've exhausted all options in attempting to bypass the CORS error that keeps popping up. When trying to implement OAuth flow and redirect my app to the Salesforce login screen, I am facing issues as the URL auto redirects from Salesforce to another Sa ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...