Requesting with Keeping Cookies using Google Apps Script (SessionFetch)

Gists

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.

// This Class is used from this main function.
function main() {
  const url = "sample URL";

  const sf = new SessionFetch();
  const res1 = sf.fetch(url);
  const res2 = sf.fetch(url); // This request is run by including Cookie retrieved from the 1st request.

  console.log(sf.history); // Here, you can see the history of these requests.
}

Testing

When you use this script, please set url. And, please create an instance of SessionFetch. In this sample script, 2 requests are run. At the 1st request, the cookie is retrieved. And, at the 2nd request, the retrieved cookie is used. Of course, in your actual situation, the URLs of 1st and 2nd requests might be required to be changed. Please check your actual situation.

When you want to retrieve the history of requests, please use sf.history.

Reference

 Share!