One of the many cool things about working in the browser is you can just drag and drop a local HTML file into it and see your work. No local server running or anything, just files and a browser, like Adam and Eve. But due to browser security settings, developing this way can still trigger CORS-related errors when you load in local files, such as an mp4.
Let's see how to eliminate pesky CORS errors while doing this most foundational style of local development!
So, I just spent about 10 minutes trying to load in a local audio file, and I kept getting the following error in the browser console:
The HTMLMediaElement passed to createMediaElementSource has a cross-origin resource, the node will output silence.
In Chrome you may see something like:
MediaElementAudioSource outputs zeroes due to CORS access restrictions for file:///Users/dengel/code/experi/dengel.m4a
I tried a few things that did not work:
- adding the
crossorigin="anonymousattribute to the
- passing in the absolute filepath to the .mp4
These attempts just ended up raising different errors. It turns out you need to look to the browser settings to get past these errors.
In Firefox, first you need to navigate to about:config in the Firefox browser, search for the privacy.file_unique_origin setting, and set it from
false by double-clicking it. Voila, super easy!
If you're working in Chrome it's a little more laborious and requires using the Terminal (I'm on a Mac, but judging from this StackOverflow post, for PowerShell users it's not much different):
- In the Chrome address bar, navigate to chrome://version
- On this page, find and copy the value of "Command Line". It will look like
/Applications/Google Chrome.app/Contents/MacOS/Google Chrome.
- Open your Terminal and paste in the file path to the Chrome executable you just copied
- If it's not recognizing the path, the spaces in the file path might need to be escaped with a forward-slash like
- Before you hit enter, two more things to add to this command
- Add the following flag to the end of your command:
- Finally, add the folder or file you want to open at the end, like
Your final command in Terminal will look something like this (assuming you're within your project folder):
$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files audio.html
If the command is successful, it should open up a Chrome window with your folder or file that you specified in the last step.
One gotcha I encountered was I needed to close my already-open instance of Chrome for the
allow-file-access-from-files flag to register.
After that, my audio file was loaded and I got on my merry way. Hope this saves you a few minutes of searching!