Skip to content

Instantly share code, notes, and snippets.

Last active Mar 11, 2016
What would you like to do?
Access CSRF token in external javascript file, using jquery.cookie.js
// base.html
<script type="text/javascript">
var csrf = "{% csrf_token %}";
$.cookie("csrfmiddlewaretoken", csrf);
// 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());
Copy link

marcusshepp commented Feb 18, 2016

requires: <script type="text/javascript" src="{% static 'js/jquery.cookie.js' %}"></script>
which you can download from:

Copy link

marcusshepp commented Feb 18, 2016

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