Skip to content

Instantly share code, notes, and snippets.

@marcusshepp
Last active March 11, 2016 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcusshepp/afee735621556fc40e24 to your computer and use it in GitHub Desktop.
Save marcusshepp/afee735621556fc40e24 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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