Sample Code for HTML and React

1. HTML with JavaScript Example

Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Streampixel Test</title>
  <style>
    iframe {
      width: 100vw;
      height: 90vh;
    }
  </style>
</head>
<body>
  <div id="container">
    <iframe id="iframe" src="https://demo.streampixel.io/demo-project" title="Iframe"></iframe>
    <button id="sendMessageButton">Send Message</button>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const iframe = document.getElementById('iframe');
      const sendMessageButton = document.getElementById('sendMessageButton');

      // Function to handle sending a message to the iframe
      const handleSendCommand = () => {
        const message = { message: 'test' };
        if (iframe.contentWindow) {
          iframe.contentWindow.postMessage(message, '*');
        }
      };

      // Event listener for messages from the iframe
      window.addEventListener('message', (event) => {
        console.log(event.data);
      });

      // Handle sending message button click
      sendMessageButton.addEventListener('click', handleSendCommand);
    });
  </script>
</body>
</html>

Explanation:

  • HTML Structure:

    • The iframe element is used to embed the StreamPixel player. It has an id of "iframe" and its src is set to a demo URL (https://demo.streampixel.io/demo-project).

    • You should replace this demo URL with the actual shareable link from your StreamPixel project page, which you can find on the project page within StreamPixel.

    • A button with the id "sendMessageButton" is included to allow the user to send a message to the application running inside the iframe.

  • JavaScript Functionality:

    • DOMContentLoaded Event: The script runs after the page's DOM is fully loaded, ensuring that all elements are available for manipulation.

    • handleSendCommand Function: This function prepares a simple message ({ message: 'test' }) and sends it to the application inside the iframe using the postMessage method.

    • Message Listener: The window.addEventListener('message', ...) listens for messages sent from the application inside the iframe and logs them to the console.

    • Button Click Event: Clicking the button triggers the handleSendCommand function, sending the message to the iframe.

  • Customization Options:

    • You can replace the button click event with any other trigger, such as an automatic message sent when the page loads, or a message sent when a user interacts with another part of the page.

This example demonstrates how to set up communication between a frontend (HTML) and an application running within an iframe using JavaScript.


2. React Example

Code:

import { useRef, useEffect, useState } from 'react';
import './App.css';

function App() {
  const iframeRef = useRef(null);
  const [iframeUrl, setIframeUrl] = useState('');
  const [urlSubmitted, setUrlSubmitted] = useState(false);

  // Function to handle sending a message to the iframe
  const handleSendCommand = () => {
    const message = { message: 'test' };
    if (iframeRef.current) {
      iframeRef.current.contentWindow.postMessage(message, '*');
    }
  };

  // Event listener for messages from the iframe
  useEffect(() => {
    const handleMessage = (event) => {
      console.log(event.data);
    };

    window.addEventListener('message', handleMessage);

    // Cleanup function to remove the event listener
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

  const handleSubmit = (event) => {
    event.preventDefault();
    if (iframeUrl.trim()) {
      setUrlSubmitted(true); 
    }
  };

  return (
    <div>
      {urlSubmitted ? (
        <>
          <iframe
            style={{ width: '100vw', height: '90vh' }}
            ref={iframeRef}
            src={iframeUrl || 'https://demo.streampixel.io/demo-project'}
            title="Iframe"
          />
          <button onClick={handleSendCommand}>Send Message</button>
        </>
      ) : (
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={iframeUrl}
            onChange={(e) => setIframeUrl(e.target.value)}
            placeholder="Iframe URL"
          />
          <button type="submit">Submit</button>
        </form>
      )}
    </div>
  );
}

export default App;

Explanation:

  • React Components and Hooks:

    • useRef Hook: iframeRef is used to reference the iframe element, allowing direct manipulation and communication with the content inside the iframe.

    • useState Hook: iframeUrl stores the URL of the iframe, and urlSubmitted tracks whether the URL has been submitted by the user.

  • Sending Commands:

    • handleSendCommand Function: This function sends a message ({ message: 'test' }) to the application running in the iframe. It accesses the iframe through iframeRef.

  • Listening for Messages:

    • useEffect Hook: Sets up an event listener for message events when the component mounts and cleans up the listener when the component unmounts.

    • handleMessage Function: Logs any messages received from the iframe to the console.

  • Handling URL Submission:

    • handleSubmit Function: This function captures the URL entered by the user, updates the iframeUrl state, and renders the iframe once the URL is submitted.

  • Conditional Rendering:

    • The component conditionally renders either the URL input form or the iframe with a "Send Message" button, depending on whether the URL has been submitted.

    • A demo URL (https://demo.streampixel.io/demo-project) is used as the default if no URL is provided. You should replace this with your actual shareable link from your StreamPixel project page.

  • Customization Options:

    • You can customize when the handleSendCommand function is triggered by replacing the button click with other logic, such as automatically sending a message after a certain condition is met, or when specific user interactions occur.

This example shows how to manage communication between a React app and an application running inside an iframe, using React hooks to manage state and refs effectively.


Customizing the Trigger for Sending Messages

In the sample codes provided below, a button is used to trigger the sending of a message to the application running inside the iframe. However, this is just one way to trigger the message.

You can customize when and how messages are sent based on any logic or conditions you define. For example:

  • Automatically Send a Message: You can set the message to be sent automatically when the page loads or after a specific amount of time.

  • User Interactions: Messages could be triggered by different user interactions, such as typing in an input field, selecting an option from a dropdown, or even just moving the mouse.

  • Application Logic: Messages could be sent when certain conditions in your application are met, like a state change, a completed task, or after receiving data from an API.

This flexibility allows you to tailor the message-sending functionality to fit the specific needs of your application.

Last updated