Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie
To address the SECURITY_ERR: DOM Exception 18
when setting a cookie, you should:
- Serve content over HTTP/HTTPS – steer clear of
file:///
URLs. - Uphold the same domain and protocol – your script and page should be consistent.
- Confirm your browser cookie settings – third-party cookies must not be blocked.
Example to set a cookie, given the right conditions:
Check these points to ensure cookies are correctly set without SECURITY_ERR
.
Understanding the Exception
SECURITY_ERR: DOM Exception 18
is primarily due to a browser's local file restriction.
-
Local vs. Server Context: HTML files loaded directly with
file://
URLs can't set cookies due to security restrictions. Instead, host your files on a local server (likehttp://localhost
) to get around these restrictions. -
Secure Contexts: Always use HTTPS, even for local development. Some browsers restrict certain features (such as geolocation or service workers) to secure contexts.
-
Browser Flags: Running Chrome with
--allow-file-access-from-files
can bypass local file restrictions. But, remember Uncle Ben's advice to Peter Parker: "With great power, comes great responsibility".
Alternatives when cookies can't be set
-
Resorting to
localStorage
: If setting cookies becomes a herculean task due to restrictions, consider usinglocalStorage
as it doesn't face similar restrictions in afile://
context. -
Browser Peculiarities: Some browsers, like Firefox or Chrome Canary, can be flexible with security measures. But remember, this is not your user's typical environment.
-
Temporarily Disabling Security Features: There are tools/browser extensions that allow you to temporarily disable certain security features. But, restore these settings before web browsing, or you might open Pandora's box of system threats.
Good Practices to Avoid Errors
-
Proper Plugin Usage: Using jQuery cookie plugins correctly is essential. Misusage can lead to unexpected security errors, like
DOM Exception 18
. -
Understanding Security Settings: Security settings vary across browsers, understanding them will help you avoid tripping over
DOM Exception 18
. -
Web Workers and Data URIs: Using web workers with data URI schemes can manage local files, but it requires caution. Now, this is where things get real.
Workarounds and Cautions
-
Inline Content: Using inline Base64 for images circumvents some security restrictions but might not hold up well for performance.
-
Environment Setup: Using developer tools with built-in servers like VS Code's Live Server extension works wonders for resource hosting and avoids
file://
URLs. -
Browser-Specific Behaviour: Security limitations can vary across browsers. It's like living in a world where no two individuals are the same. Always test multiple browsers... diversity is key!
Was this article helpful?