πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Implementing PDF file download using JavaScript and resolving CORS policy error

3 replies
Last updated: Dec 27, 2021
Hey everyone, I am going to implement PDF file download using javascript and here's the code snippets. But I am getting CORS policy error. Any idea?
  const download = (url, name, redirectTo) => {
    if (!url) {
      throw new Error("Resource URL not provided! You need to provide one");
    }
    fetch(url)
      .then(response => response.blob())
      .then(blob => {
        setFetching(false);
        const blobURL = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = blobURL;
        a.style = "display: none";

        if (name && name.length) a.download = name;
        document.body.appendChild(a);
        a.click();
				navigate(redirectTo)
      })
      .catch(() => setErrors(["Something went wrong in fetching file data for download."]));
  };
Dec 27, 2021, 8:32 PM
user A
Great! thank you. I didn't know this great feature on sanity management board. It's working now.
Dec 27, 2021, 11:05 PM
user A
Great! thank you. I didn't know this great feature on sanity management board. It's working now.
Dec 27, 2021, 11:05 PM
Great! I’m glad things are working for you. πŸ™Œ
Dec 27, 2021, 11:06 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?