Most of the script above is to replicate the request, if you're familiar with js it shouldn't be that hard/surprising and I'm sure burp has some kind of feature or extension to convert a request into JavaScript Code.
But the interesting part (for me at least) is this line:
var token = this.responseText.match(/name="csrf" type="hidden" value="(\w+)"/)[1];
This line parses the html of the website that is currently open and matches a regex-like expression. This expression looks for a line with the attributes name=csrf and type=hiden and extracts the value: our csrf token.
So even if it's randomly generated, we can get it
#xss #csrf #hacking #cybersecurity #crosssiterequestforgery #crosssitescripting #pentesting