0

I am trying to load images from in my react component but I am getting this error Refused to load the image 'blob:https://canister_id.icp0.io/76684b08-27e4-4c3f-b260-16847c3b7df6' because it violates the following Content Security Policy directive: "img-src 'self' data:"..

I tried fixing the problem by updating the metadata to this:

   <meta
      http-equiv="Content-Security-Policy"
      content="default-src *;
   img-src * 'self' data: https: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' *;
   style-src  'self' 'unsafe-inline' *"
    />

But the error still ramained as above.

I should also add that the react frontend is in a motoko smart contract, I am coverting the images from bytes data to the blobs in my component like so:

   const getAllProducts = async (): Promise<Product[]> => {
    setLoading(true);
    try {
      const products = await marketplace_backend.getProducts();

      const convertImage = (image: Uint8Array | number[]): string => {
        const imageContent = new Uint8Array(image);
        const blob = new Blob([imageContent.buffer], { type: "image/png" });
        return URL.createObjectURL(blob);
      };

      const productsWithUrl = products.map((product) => ({
        ...product,
        image: convertImage(product.image),
        smallImages: {
          image1: convertImage(product.smallImages.image1),
          image2: convertImage(product.smallImages.image2),
          image3: convertImage(product.smallImages.image3),
        },
      }));
      setProducts(productsWithUrl);
      console.log(productsWithUrl, "converted images");
      setLoading(false);
      return productsWithUrl;
    } catch (e) {
      setLoading(false);
      console.log(e, "Error");
    }
  };

Maybe there is somewthing I should also do on the function here where the images are being converted and solve the problem?

Enoch
  • 11
  • 1
  • 3
  • It looks fine to me, so far. Can you try, just `` ? (thinking) – Smartis has left SO again May 17 '23 at 11:50
  • @Smartis it was fine for sure, in my smart contract I was putting those settings in the wrong place, there is the .ic-assets.json5 file that will be in my assets which contains the CSP and that's the one I just had to add blob: to it and it worked. – Enoch May 21 '23 at 14:02

1 Answers1

1

There is likely another CSP served as a response header. Adding another one in a meta tag can only make it stricter. You need to identify how the existing CSP is set and updated that one.

Halvor Sakshaug
  • 2,583
  • 1
  • 6
  • 9
  • yeah that was the issue, there is the .ic-assets.json5 file in my assets which contains the CSP and I just had to add blob: to it and everything worked, thanks – Enoch May 21 '23 at 13:57