Last active
March 11, 2016 23:49
-
-
Save marcusshepp/afee735621556fc40e24 to your computer and use it in GitHub Desktop.
Access CSRF token in external javascript file, using jquery.cookie.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// base.html | |
<script type="text/javascript"> | |
$(document).ready(function(){ | |
var csrf = "{% csrf_token %}"; | |
$.cookie("csrfmiddlewaretoken", csrf); | |
}); | |
</script> | |
// script.js | |
var csrf_func = function(){ | |
// need to stick the element string back into the DOM | |
// then extract it out enabling the `.value` to work. | |
var csrf = $.cookie("csrfmiddlewaretoken"); | |
var wrapper = document.createElement("div"); | |
wrapper.innerHTML = csrf; | |
var csrf_element = wrapper.firstChild; | |
return csrf_element.value; | |
} | |
console.log("csrfmiddlewaretoken: ", csrf_func()); |
if anyone knows how to get out the value="<this>"
from the string in line #13 other than the way I did it please say.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requires:
<script type="text/javascript" src="{% static 'js/jquery.cookie.js' %}"></script>
which you can download from: https://github.com/carhartl/jquery-cookie