Integrate a custom OpenAI chatbot widget on your webpage easily with HTML and JavaScript.
Add an AI-powered chat widget to any website in minutes. This script uses the OpenAI API to create an interactive chatbot experience.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ChatGPT Widget</title>
<style>
#chat-widget {
position: fixed;
bottom: 20px;
right: 20px;
width: 350px;
height: 500px;
border: 1px solid #ddd;
border-radius: 10px;
background: white;
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
display: flex;
flex-direction: column;
}
#chat-messages {
flex: 1;
overflow-y: auto;
padding: 15px;
}
.message {
margin: 10px 0;
padding: 10px;
border-radius: 8px;
}
.user { background: #007bff; color: white; text-align: right; }
.bot { background: #f1f1f1; }
</style>
</head>
<body>
<div id="chat-widget">
<div id="chat-messages"></div>
<input type="text" id="user-input" placeholder="Ask me anything...">
</div>
<script>
const API_KEY = "YOUR_OPENAI_API_KEY";
async function sendMessage(message) {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{role: "user", content: message}]
})
});
const data = await response.json();
return data.choices[0].message.content;
}
document.getElementById("user-input").addEventListener("keypress", async (e) => {
if (e.key === "Enter") {
const userMsg = e.target.value;
// Display user message
document.getElementById("chat-messages").innerHTML +=
`<div class="message user">${userMsg}</div>`;
// Get bot response
const botMsg = await sendMessage(userMsg);
document.getElementById("chat-messages").innerHTML +=
`<div class="message bot">${botMsg}</div>`;
e.target.value = "";
}
});
</script>
</body>
</html>