Requesting with Keeping Cookies using Google Apps Script (SessionFetch)
This is a sample script for requesting with keeping cookies using Google Apps Script.
This might be similar to requests.Session" of Python. Ref
Sample script
This is Class SessionFetch.
/**
* UrlFetchApp is run by keeping Cookie.
*/
class SessionFetch {
constructor() {
this.cookie = "";
this.his = [];
}
/**
* Request URL.
* @param {string} url URL
* @param {object} params Object
* @return {UrlFetchApp.HTTPResponse}
*/
fetch(url, params = {}) {
if (this.cookie != "") {
if (!params.headers) {
params.headers = { Cookie: this.cookie };
} else if (!params.headers["Cookie"]) {
params.headers["Cookie"] = this.cookie;
}
}
this.his.push({ date: new Date(), url, params });
const res = UrlFetchApp.fetch(url, params);
this.cookie = res.getAllHeaders()["Set-Cookie"] || "";
return res;
}
/**
* Return history of fetch requesting in this Class.
* @return {array} History.
*/
get history() {
return this.his;
}
}
This is a sample script for using Class SessionFetch.