Created
April 12, 2023 18:08
-
-
Save lsloan/157d143f3cc36f82b0b1295dda1936cd to your computer and use it in GitHub Desktop.
Run a Canvas API query from the browser using CSRF token set by the site.
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
var csrfToken = getCsrfToken(); | |
console.log('crsfToken', csrfToken); | |
fetch('/api/v1/conversations/unread_count', { | |
method: 'GET', | |
credentials: 'include', | |
headers: { | |
"Accept": "application/json", | |
"X-CSRF-Token": csrfToken | |
} | |
}) | |
.then(status) | |
.then(json) | |
.then(function(data) { | |
console.log(data); | |
}) | |
.catch(function(error) { | |
console.log('Request failed', error); | |
}); | |
/* | |
* Find the cookie containing csrf_token and return the value. | |
* See: https://community.canvaslms.com/thread/22500-mobile-javascript-development | |
*/ | |
function getCsrfToken() { | |
var csrfRegex = new RegExp('^_csrf_token=(.*)$'); | |
var csrf; | |
var cookies = document.cookie.split(';'); | |
for (var i = 0; i < cookies.length; i++) { | |
var cookie = cookies[i].trim(); | |
var match = csrfRegex.exec(cookie); | |
if (match) { | |
csrf = decodeURIComponent(match[1]); | |
break; | |
} | |
} | |
return csrf; | |
} | |
/* | |
* Return a promise if response status is OK; return an error if rejected. | |
*/ | |
function status(response) { | |
if (response.status >= 200 && response.status < 300) { | |
return Promise.resolve(response) | |
} else { | |
return Promise.reject(new Error(response.statusText)) | |
} | |
} | |
/* | |
* Return JSON from response. | |
*/ | |
function json(response) { | |
return response.json() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a reformatted version of a program which was found at: https://learntech.medsci.ox.ac.uk/wordpress-blog/working-with-the-canvas-api-in-plain-js-pt-1