2

I am trying to extract the csrf token from a Django powered webpage using javascript.

My html template looks like this:

<div class = "debugging">
  <p id = "csrf">{% csrf_token %}</p>
</div>

When I use this script below, I can see the token value in the console, but can't actually extract it:

<script>
var csrfToken = document.getElementById("csrf");
console.log(csrfToken.innerHTML);
</script>

It returns in console:

<input type="hidden" name="csrfmiddlewaretoken" 
value="AAIawsx1XysoQpDyIqyzdPe3npopNCHRzFBQdvUdlr4TUPEq3Sr5C5bFqc">

So I tried:

var csrfToken = document.getElementById("csrf").attributes[0].value;
var csrfToken = document.getElementById("csrf").value;

both returned "undefined"

Any help is appreciated!

3 Answers 3

4

Your django seems to create an input element holding your token, so just select that using querySelector and read its value:

var csrfToken = document.querySelector("#csrf input").value;

Since your django code also generates a name="csrfmiddlewaretoken" on that input element, you can also do this:

var csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value;
Sign up to request clarification or add additional context in comments.

Comments

1

I tried this in new Laravel. it is Vanilla JS and can be called anywhere. In JS or blade file.

var csrf = document.querySelector('meta[name="csrf-token"]').content;

Comments

0

You could have used {{ csrf_token }} instead of {% csrf_token %} if you intend to get only the token value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.