Problem Overview
The reason is simply because chrome-extension://
represents just the scheme (protocol)—similar to http://
, https://
, etc.—not a complete origin (which includes the domain and port as well) to be used in the CORS mechanism.
Solution 1
Hence, as you already figured out, you would need to define the origin of your chrome extension similar to the one below. If you would like to maintain the unique ID of an extension during development, instead of having random chrome extension IDs and needing to change the origin in the server side each time, please have a look at the relevant chrome extensions documentation on keeping a consistent extension ID.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"chrome-extension://dpcnaflfhdkdeijjglelioklbghepbig"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Related answers around this topic can be found here, as well as here and here.
Solution 2
As described in this answer, instead of using the allow_origins
argument of the CORSMiddleware
(the implementation of the CORSMiddleware
class can be found in Starlette's source code here and the relevant Starlette documentation here), you could use the allow_origin_regex
argument, which allows you to define a regex pattern to match against origins that should be permitted to make cross-origin requests. Example:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origin_regex="chrome-extension://.*",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Beware that using this solution with the regex provided above would allow any chrome extension to communicate with your FastAPI server (using cross-origin requests). Hence, if that's something that you wouldn't want to, especially in production (not during development), you may choose to use Solution 1 instead.