Search code examples
htmlcsscorsfont-face

Using Imported Fonts in a Google App


I am creating a web app using Google Apps Script. When I wanted to import a photo from Google Docs, I followed the advice from this question and it worked perfectly. I thought a similar process would work for using a custom font hosted on Docs, but it throws a CORS exception.

The relevant code:

@font-face {
    font-family: MyCustomFont;
    src: url("https://drive.google.com/uc?export=download&id=1r2a5nd6om75url39428dfju4");
} 

#headBanner {
    font-family: MyCustomFont;
}
<div id="headBanner"> 
  <p>This text should be in MyCustomFont</p>
</div>

The error it throws is: "Access to Font at '[URL in font]' from origin '[Google Script page I'm using]' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[Google Script page I'm using]' is therefore not allowed access."

How could I fix this? I just find it perplexing that it would throw a CORS exception for the font file but not for the picture.


Solution

  • Font files, along with AJAX requests using fetch are the only things that use CORS. Image requests and static inline requests for JavaScript (via tags) and CSS do not invoke CORS.

    In this case, there is nothing you can do, short of (as @andrei-gheorghiu suggests) downloading the font file manually, saving it to your server and then accessing it from there. Whilst you can do that technically, it would technically be stealing. Hence his use of "Can, not may"...

    Fun fact - CORS was basically invented for the specific use-case you've come across - so that 'font factories' could design fonts (which cost them money, obviously) and then be able to allow/deny access to those font files, depending on whether you have paid a license fee.

    No doubt not the answer you wanted, but the answer nevertheless.