Phantombuster event stream demo

https://hub.phantombuster.com/

by papsss

HTML

<h3>Phantombuster event stream demo</h3>

<p style="border: 1px solid #ccc; width: 450px; padding: 20px;">
  This demo showcases the use of <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">EventSource</a> to launch a Phantombuster agent and get back console output in real time.
  <br /><br />
  The endpoint is <a href="http://docs.phantombuster.com/en/latest/api.html#agent-id-launch">documented here</a>.
  <br /><br />
  Get your API key in your <a href="https://phantombuster.com/settings">settings page</a>.
  <br /><br />
  View the page source to get the code.
</p>

<p>
  Your API key <input id="api_key" type="text" style="width: 300px;" />
  ID of agent to launch <input id="agent_id" type="text" style="width: 50px;" />
  <input id="launch_button" type="button" value="Launch" />
</p>

<p>Stream status: <span id="status">not connected</span></p>

<p>Output:</p>
<pre id="output"></pre>

JavaScript

var eventSource = null;

$('#launch_button').click(function() {

  // stop the connection if we were already connected
  if (eventSource) {
    eventSource.close();
    $('#status').text('not connected');
    $('#output').empty();
  }

  var apiKey = $('#api_key').val();
  var agentId = $('#agent_id').val();

  // start new connection to the Phantombuster API in event-stream mode
  eventSource = new EventSource('https://phantombuster.com/api/v1/agent/' + agentId + '/launch?output=event-stream&key=' + apiKey);

  eventSource.onopen = function() {
    $('#status').text('connected, agent queued'); // when the connection opens, we know the agent was queued successfully
  }

  eventSource.onmessage = function(e) {
    $('#status').text('connected, agent running'); // when we receive the first message, we know the agent is running
    $('#output').text($('#output').text() + e.data);
  }

  eventSource.onerror = function() {
    $('#status').text('not connected');
    eventSource.close();
  }

});