Skip to content

Commit 3e374b2

Browse files
committed
Check the cookie for the CSRF token.
1 parent 94516f2 commit 3e374b2

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

django_unicorn/static/js/unicorn.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,17 @@ const Unicorn = (() => {
4040
* Get the CSRF token used by Django.
4141
*/
4242
function getCsrfToken() {
43+
// Default to looking for the CSRF in the cookie
44+
const cookieKey = "csrftoken=";
45+
const csrfTokenCookie = document.cookie.split(";").filter((item) => item.trim().startsWith(cookieKey));
46+
47+
if (csrfTokenCookie.length > 0) {
48+
return csrfTokenCookie[0].replace(cookieKey, "");
49+
}
50+
51+
// Fall back to check for the CSRF hidden input
4352
const csrfElements = document.getElementsByName("csrfmiddlewaretoken");
53+
4454
if (csrfElements && csrfElements.length > 0) {
4555
return csrfElements[0].getAttribute("value");
4656
}

0 commit comments

Comments
 (0)