Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active May 11, 2023 20:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/6202470a2bb4d22d1b195bb20bf8390c to your computer and use it in GitHub Desktop.
Save tanaikech/6202470a2bb4d22d1b195bb20bf8390c to your computer and use it in GitHub Desktop.
Requesting with Keeping Cookies using Google Apps Script (SessionFetch)

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.

// 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment