/\  Semaphor

Web Component

Embed Semaphor dashboard in your HTML project

This example is based on the assumption that you are working with vanilla JavaScript in an HTML environment. It involves a script that fetches the token and passes it to the auth-token attribute once the token is retrieved.

Let's first initialize a vanilla JavaScript project using Vite's guide.

npm create vite@latest
 
 Project name: vite-vanilla
 Select a framework: Vanilla
 Select a variant: JavaScript
 
Scaffolding project in /sourcecode/semaphor-demos/vite-vanilla...
 
Done. Now run:
 
cd vite-vanilla
npm install
npm run dev

1. Install Semaphor Package

After running the above commands, open the project in your editor and install the semaphor package.

npm install semaphor

2. Obtain the Auth Token

First, create a dashboard.js file at the root of your project and paste the following code. This code retrieves the AuthToken, which provides access to the dashboard.

Note: auth-token is used as an attribute of a web component. Web components adhere to the kebab-case naming convention, which involves writing words in lowercase and separating them with hyphens -. This convention is used for attribute names and CSS class names, as camelCase is not supported.

dashboard.js
import { DashboardWC } from 'semaphor'; // import the web component - denoted by WC suffix.
customElements.define('semaphor-dashboard', DashboardWC); // define the web component.
 
document.addEventListener('DOMContentLoaded', function () {
  // Constants for the fetch call
  const DASHBOARD_ID = 'd_cf007a8b-19bc-46ad-8787-2915445b7b86'; // Replace with your actual dashboard ID
  const DASHBOARD_SECRET = 'ds_f32f0b30-b7e1-40f9-ba6a-9804a5b9d635'; // Replace with your actual dashboard secret
  const TOKEN_URL = 'https://semaphor.cloud/api/v1/token';
 
  // Function to fetch token
  async function fetchToken() {
    try {
      const response = await fetch(TOKEN_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          dashboardId: DASHBOARD_ID,
          dashboardSecret: DASHBOARD_SECRET,
        }),
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
 
      const token = await response.json();
      if (token?.accessToken) {
        updateDashboardAuthToken(token);
      }
    } catch (error) {
      console.error('There was an error!', error);
    }
  }
 
  // Function to update the web component's auth-token attribute
  function updateDashboardAuthToken(token) {
    const authTokenString = JSON.stringify(token);
    const dashboardElement = document.getElementById(DASHBOARD_ID);
    if (dashboardElement) {
      dashboardElement.setAttribute('auth-token', authTokenString);
    } else {
      console.error('Dashboard element not found');
    }
  }
 
  // Fetch and set the token when the DOM content is fully loaded
  fetchToken();
});

Security Note

Do not expose DASHBOARD_SECRET in client-side code in production. Use a backend service to fetch the token securely.

3. Render the Dashboard

And finally, let's add the following three lines to the index.html file as below:

  • Styles <link rel="stylesheet" href="./node_modules/semaphor/dist/style.css" /> initalizes the styles. This is IMPORTANT for your dashboard styles to load properly.
  • Web Component <semaphor-dashboard id="d_cf007a8b-19bc-46ad-8787-2915445b7b86" /> is the web component that renders the dashbaord,
  • Token <script type="module" src="./dashboard.js"></script> references the code fetches the AuthToken.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>

    <link rel="stylesheet" href="./node_modules/semaphor/dist/style.css" />
  </head>
  <body>
    <div id="app"></div>

    <semaphor-dashboard id="d_cf007a8b-19bc-46ad-8787-2915445b7b86" />

    <script type="module" src="./dashboard.js"></script>
  </body>
</html>

Now, you can run the app by typing the following command in your terminal window.

npm run dev

Passing styles

Create a custom class in your style.css.

.myClass {
  border-color: orange;
}

And then you can reference this class in dashboard.js, like so.

import './style.css';
 
const customStyle = {
  default: {
    dashboardCard: 'myClass',
  },
};
 
dashboardElement.setAttribute('style', JSON.stringify(customStyle));

Since the style attribute is a complex type, you need to pass the JSON string value to the style attribite.


Key Considerations

  • Security: Keep the DASHBOARD_SECRET secure and do not expose it in client-side code in production. The example above is for demonstration purposes. When deploying in production, obtain the authentication token from a secure, server-side environment.
  • Error Handling: The code includes basic error handling for the fetch call and element selection. Depending on your application's complexity and requirements, you might want to implement more sophisticated error handling.
  • DOM Ready: The script waits for the DOMContentLoaded event, ensuring the DOM is fully loaded before attempting to manipulate elements or fetch data. This is crucial for accessing elements that are defined later in the HTML document.

On this page