Skip to content

Instantly share code, notes, and snippets.

@marcusshepp marcusshepp/csrf.js

Last active Mar 11, 2016
Embed
What would you like to do?
Access CSRF token in external javascript file, using jquery.cookie.js
// 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());
@marcusshepp

This comment has been minimized.

Copy link
Owner Author

marcusshepp commented Feb 18, 2016

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

@marcusshepp

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.