Add copilot to any text input field with a send button
This step-by-step guide explains how to trigger Website Copilot using a text input field and a Send button. When a user presses Enter or clicks the Send button, Copilot will launch and respond automatically.
Note:Before starting, make sure you've embedded Website Copilot by following the Website Copilot deployment instructions. This ensures all required scripts are properly loaded.
- Add a text input field with the attribute
data-cgpt-ai-assistant-input
, and a button with a unique id:
Here is an example of how it should look:
<input id="cool-id" data-cgpt-ai-assistant-input></input>
<button id="cool-arrow">β€</button>
Important Notes:The id attributes on both input and button are crucial as they will be used in the next step.
Both ids must have a value. In the example above, they are set to "cool-id" and "cool-arrow".
- Add a script that will listen for both the Enter key in the text input, and Send button, and use them to open your AI Agent. Ensure the script uses the same ids as your text input field and button from Step 2.
Here is the script you can use:
<script>
document.addEventListener('DOMContentLoaded', function() {
const inputElement = document.getElementById('cool-id')
const buttonElement = document.getElementById('cool-arrow')
function sendQuery() {
const inputValue = inputElement.value
if (inputValue.trim()) {
document.dispatchEvent(
new CustomEvent('CustomGPTSendQuery', { detail: inputValue })
)
inputElement.value = ''
}
}
inputElement.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
sendQuery()
}
})
buttonElement.addEventListener('click', sendQuery)
})
</script>
The script should be placed after thebody
section of your webpage.Ensure the ids in
getElementById
matches the "id" of your input field and button from the Step 2.
Example
Here is how an example page would look like:
<html>
<body>
<script src="https://cdn.customgpt.ai/js/ai-assistant.js" defer="" p_id="AGENT_ID" p_key="AGENT_KEY"></script>
<input id="cool-id" placeholder="Ask me somethingβ¦" data-cgpt-ai-assistant-input></input>
<button id="cool-arrow">β€</button>
</body>
<script>
document.addEventListener('DOMContentLoaded', function() {
const inputElement = document.getElementById('cool-id')
const buttonElement = document.getElementById('cool-arrow')
function sendQuery() {
const inputValue = inputElement.value
if (inputValue.trim()) {
document.dispatchEvent(
new CustomEvent('CustomGPTSendQuery', { detail: inputValue })
)
inputElement.value = ''
}
}
inputElement.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
sendQuery()
}
})
buttonElement.addEventListener('click', sendQuery)
})
</script>
</html>
Updated about 1 month ago