Widgetsāthose little UI elements like chat popups and notificationsāare super handy. Hereās a quick way to build and serve a widget using Node.js, making it embeddable with a simple <script>
tag.
1ļøā£ Set Up the Server
mkdir widget-server && cd widget-server
npm init -y
npm install express
Create server.js
:
const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;
app.get('/widget', (req, res) => res.sendFile(path.join(__dirname, 'widget.html')));
app.get('/embed.js', (req, res) => {
res.setHeader('Content-Type', 'application/javascript');
res.send(`
(function() {
let iframe = document.createElement('iframe');
iframe.src = 'http://localhost:${PORT}/widget';
iframe.style = 'width:320px;height:200px;border:none;position:fixed;bottom:20px;right:20px;z-index:9999;';
document.body.appendChild(iframe);
})();
`);
});
app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));
2ļøā£ Create the Widget
Create widget.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Widget</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 10px; }
button { background: #007BFF; color: #fff; padding: 10px; border: none; cursor: pointer; }
</style>
</head>
<body>
<h3>My Widget</h3>
<button>Click Me</button>
</body>
</html>
3ļøā£ Embed It Anywhere
<script src="http://localhost:3000/embed.js"></script>
Run the server:
node server.js
This will load the widget inside an iframe on any webpage. š****
Top comments (0)