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!
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!
Share Improve this question asked Oct 7, 2018 at 20:37 MattGMattG 1,9326 gold badges29 silver badges55 bronze badges3 Answers
Reset to default 4Your 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;
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;
You could have used
{{ csrf_token }}
instead of
{% csrf_token %}
if you intend to get only the token value
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744093141a4557454.html
评论列表(0条)