Introduction
Widgets are powerful ways to embed interactive functionality into static web pages. They allow developers to build modular components that can be reused across multiple websites, reducing redundancy and improving maintainability. One common scenario in widget implementation is the need to pass variables—such as configuration settings, API keys, or user-specific data—from the static page to the widget.
In this blog, we’ll explore how to securely pass variables from a static page to a widget, outline common use cases, and provide practical implementation examples.
Why Pass Variables from a Static Page to a Widget?
Imagine creating a reusable chat widget, analytics widget, or payment module. These widgets may require data such as:
- A unique key or token for authentication.
- User-specific IDs for personalization.
- Random numbers for ensuring unpredictability or preventing cache collisions.
By passing variables dynamically, developers can:
- Adapt widgets to different contexts.
- Simplify widget reuse across multiple websites.
- Reduce hard coding and enhance maintainability.
Implementation: Passing Variables Step-by-Step
- Create the Static HTML Page - first, generate a random number dynamically using JavaScript and assign this number to a data attribute of the where the widget will render.
- So modify the html file accordingly:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Widget</title>
<script>
document.addEventListener("DOMContentLoaded", function () {
const randomNumber = Math.floor(Math.random() * 1000);
const widgetRoot = document.getElementById("widget-root");
if (widgetRoot) {
widgetRoot.setAttribute("data-random-number", randomNumber);
console.log("Random number of the static page:", randomNumber);
}
});
</script>
</head>
<body>
<h1>Static Page with Random Number in Widget</h1>
<!-- Div to hold the React widget -->
<div id="widget-root"></div>
<!-- Include the bundled React app -->
<script defer="defer" src="bundle.min.js"></script>
</body>
</html>
- In the React app, fetch the data-random-number attribute from the root element and change the code in the App.tsx file:
import { useEffect } from 'react';
import { Widget, addResponseMessage } from "react-chat-widget";
import "react-chat-widget/lib/styles.css";
function App() {
useEffect(() => {
const randomNumber = document.getElementById("widget-root")?
.getAttribute("data-random-number");
console.log("Random number from static page:", randomNumber);
// Display the random number in the chat widget or use it as needed
addResponseMessage(`Welcome! Your random number is: ${randomNumber}`);
}, []);
const handleNewUserMessage = (newMessage: string) => {
console.log(`New message received: ${newMessage}`);
};
return (
<Widget
handleNewUserMessage={handleNewUserMessage}
title="Random Number Widget"
subtitle="Your session is unique!"
/>
);
}
export default App;
- Finally, bundle the Widget - Use Webpack to bundle the React widget into a bundle.min.js file, which can be included in the static page, and change the webpack.config.js file accordingly:
const path = require("path");
module.exports = {
entry: path.join(__dirname, "src/index.tsx"),
output: {
path: path.join(__dirname, "dist"),
filename: "bundle.min.js",
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: "ts-loader",
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
};
- Build the widget using "npm run build".
- Include the bundle.min.js file in your static HTML.
- Open the static page in a browser and the React widget should display the random number passed from the static page.
Conclusion
Passing variables from static pages to widgets is essential for building flexible, dynamic, and modular components. By following the outlined steps, developers can ensure that their widgets integrate seamlessly into any environment while remaining secure and efficient. Widgets are a cornerstone of modern web development. With a little planning and care, they can be built to adapt to any context dynamically and securely.
Top comments (0)