Retrieving Data from Content-Type of 'text/event-stream' using Javascript and Google Apps Script

Gists

This is a sample script for retrieving the data from Content-Type of ’text/event-stream’ using Javascript and Google Apps Script.

In the current stage, UrlFetchApp of Google Apps Script cannot be retrieved the data from Content-Type of ’text/event-stream’. This sample script can be used for achieving this as a workaround.

This sample script uses EventSource. So this script uses a dialog on Google Docs files (This sample uses Google Spreadsheet.).

Usage

1. Prepare Spreadsheet.

Create new Google Spreadsheet.

2. Sample script.

Copy and paste the following script to the script editor of Spreadsheet.

Code.gs

// Please run this function.
function main() {
  SpreadsheetApp.getUi().showModalDialog(
    HtmlService.createHtmlOutputFromFile("index"),
    "sample"
  );
}

function run(data) {
  DriveApp.createFile("sample.txt", JSON.stringify(data));
}

index.html

Please set the URL of Content-Type of text/event-stream.

Values are retrieving now. Please wait. After the values were retrieved, this
dialog is automatically closed.
<script>
  const url = "###"; // Please set URL of "text/event-stream".
  const max = 3; // In this value, retrieve the data from 3 streamed data.

  const source = new EventSource(url);
  source.onopen = (e) => console.log("start");
  source.onerror = (err) => console.log(err);
  const ar = [];
  let i = 0;
  source.onmessage = (e) => {
    if (i < max && source.readyState != 2) {
      ar.push(e.data);
      i++;
    } else {
      source.close();
      console.log({ len: ar.length });
      google.script.run
        .withSuccessHandler((_) => {
          console.log("Done.");
          google.script.host.close();
        })
        .run(ar);
    }
  };
</script>

3. Testing.

When the above script is run, 3 stream data are retrieved and create it as a text file.

References

 Share!