Getting started with chrome.printing API

Check print job status

Task 5

20 minutes

Note: An event is fired when the status of the job is changed. This is only fired for the jobs created by this extension.

Next, you’ll create a table to show all print jobs from this extension in the printers.html.

Update your printers.html with the following code:

html
<!doctype html>
<html>
  <head>
    <title>Printers</title>
    <link href="printers.css" rel="stylesheet" type="text/css" />
    <script src="printers.js"></script>
  </head>

  <body>
    <h2>Print Job:</h2>
    <p>
      On some systems, the print job may leave the queue too quickly to be
      visible in this list.
    </p>
    <div id="printJob">
      <table id="printJobTable">
        <thread>
          <tr>
            <th>Cancel</th>
            <th>Job Id</th>
            <th>Status</th>
          </tr>
        </thread>
        <tbody id="printJobTbody"></tbody>
      </table>
    </div>

    <h2>Printers:</h2>
    <div id="printers">
      <table id="printersTable">
        <thead>
          <tr>
            <th>Print</th>
            <th>Id</th>
            <th>Name</th>
            <th>Description</th>
            <th>URI</th>
            <th>Source</th>
            <th>Default</th>
            <th>Recently used</th>
            <th>Capabilities</th>
            <th>Supports trim</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="tbody" />
      </table>
    </div>
  </body>
</html>

Next, add a listener in printers.js to handle the job status change event and update the jobs table:

function addCell(parent) {
  const newCell = document.createElement('td');
  parent.appendChild(newCell);
  return newCell;
}

function onPrintButtonClicked(printerId, dpi, performTrim) {
  /* ... submit the print job code added in the previous step ... */


  chrome.printing.onJobStatusChanged.addListener((jobId, status) => {
    console.log(`jobId: ${jobId}, status: ${status}`);
    let jobTr = document.getElementById(jobId);
    if (jobTr == undefined) {
      jobTr = document.createElement('tr');
      jobTr.setAttribute('id', jobId);

      const cancelTd = addCell(jobTr);
      let cancelBtn = createButton('Cancel', () => {
        onCancelButtonClicked(jobId);
      });
      cancelBtn.setAttribute('id', `id ${jobId}-cancelBtn`);
      cancelTd.appendChild(cancelBtn);

      const jobIdTd = addCell(jobTr);
      jobIdTd.appendChild(document.createTextNode(jobId));

      let jobStatusTd = addCell(jobTr);
      jobStatusTd.id = `${jobId}-status`;
      jobStatusTd.appendChild(document.createTextNode(status));

      document.getElementById('printJobTbody').appendChild(jobTr);
    } else {
      document.getElementById(`${jobId}-status`).innerText = status;
      if (status !== 'PENDING' && status !== 'IN_PROGRESS') {
        jobTr.remove();
      }
    }
  });
}

Your turn