Sure! I'll help you modify your existing code to capture a screenshot whenever the user presses the Enter key or clicks the Send button. This way, every time a user sends a question, the current state of their shared screen will be captured and included in the analysis.
Here's the complete updated code with the necessary changes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Image Analyzer Chat</title>
<style>
/* General Styling */
body, html {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
margin: 0;
padding: 0;
height: 100%;
background-color: #ffffff;
color: #37352f;
}
.container {
display: flex;
height: 100%;
}
.sidebar {
width: 240px;
background-color: #fbfbfa;
padding: 14px;
box-shadow: inset -1px 0 0 rgba(0, 0, 0, 0.05);
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 10px;
}
.sidebar .logo {
font-size: 18px;
font-weight: 600;
margin-bottom: 30px;
text-align: center;
}
.menu-item {
padding: 10px;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.2s;
user-select: none;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
}
.menu-item:hover {
background-color: rgba(55, 53, 47, 0.1);
}
.menu-item.active {
background-color: rgba(55, 53, 47, 0.15);
}
.content {
flex-grow: 1;
padding: 40px 60px;
overflow-y: auto;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
h1 {
font-size: 36px;
font-weight: 700;
margin-bottom: 20px;
line-height: 1.2;
}
p {
font-size: 16px;
line-height: 1.5;
color: #37352f;
margin-bottom: 24px;
}
#chat-container {
flex-grow: 1;
overflow-y: auto;
margin-bottom: 20px;
padding-right: 10px;
}
.chat-message {
margin-bottom: 15px;
padding: 12px 16px;
border-radius: 8px;
max-width: 80%;
word-wrap: break-word;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.user-message {
background-color: #e6f3ff;
align-self: flex-end;
}
.ai-message {
background-color: #f0f0f0;
align-self: flex-start;
}
#user-input {
width: 100%;
padding: 12px 16px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 8px;
margin-bottom: 10px;
box-sizing: border-box;
}
#send-btn {
padding: 12px 24px;
font-size: 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.2s;
}
#send-btn:hover {
background-color: #0056b3;
}
#images {
margin-top: 40px;
}
#images h2 {
font-size: 28px;
font-weight: 600;
margin-bottom: 16px;
}
.screenshot {
margin-bottom: 20px;
border: 1px solid rgba(55, 53, 47, 0.16);
padding: 12px;
border-radius: 8px;
background-color: #fbfbfa;
}
.screenshot img {
max-width: 100%;
height: auto;
display: block;
border-radius: 5px;
}
#share-screen-btn {
padding: 10px 14px;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.2s;
user-select: none;
background-color: #fbfbfa;
color: #37352f;
text-align: center;
font-size: 16px;
border: 1px solid #ccc;
width: 100%;
margin-top: auto;
}
#share-screen-btn:hover {
background-color: rgba(55, 53, 47, 0.08);
}
#share-screen-btn.active {
background-color: rgba(55, 53, 47, 0.15);
}
.image-tab {
display: flex;
align-items: center;
padding: 10px 14px;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.2s;
user-select: none;
font-size: 16px;
background-color: #fbfbfa;
border: 1px solid #ccc;
}
.image-tab:hover {
background-color: rgba(55, 53, 47, 0.08);
}
.image-tab .star-icon {
margin-right: 8px;
color: gold;
font-size: 18px;
}
.loader {
border: 4px solid #f3f3f3;
border-top: 4px solid #37352f;
border-radius: 50%;
width: 24px;
height: 24px;
animation: spin 1s linear infinite;
display: inline-block;
vertical-align: middle;
margin-left: 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Scrollbar Styling */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
</style>
</head>
<body>
<div class="container">
<div class="sidebar">
<div class="logo">Image Analyzer Chat</div>
<div class="image-tab">
<span class="star-icon">★</span>
Images
</div>
<button id="share-screen-btn">Share Screen</button>
</div>
<div class="content">
<h1>Image Analysis Chat</h1>
<p>
Share your screen and ask questions about the images you see. The AI will analyze the image based on your question and provide answers.
</p>
<div id="chat-container"></div>
<input type="text" id="user-input" placeholder="Ask a question about the image...">
<button id="send-btn">Send</button>
<div id="images">
<h2>Captured Image</h2>
<!-- Screenshot will be appended here -->
</div>
<!-- Hidden Video Element to Capture Shared Screen -->
<video id="shared-screen-video" autoplay style="display: none;"></video>
</div>
</div>
<script>
// Replace with your actual API key
const GEMINI_API_KEY = 'YOUR_GEMINI_API_KEY_HERE';
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent';
let sharedStream = null;
const videoElement = document.getElementById('shared-screen-video');
let lastCapturedImage = null;
function shareScreen() {
if (sharedStream) {
stopScreenSharing();
return;
}
navigator.mediaDevices.getDisplayMedia({ video: true })
.then(stream => {
sharedStream = stream;
videoElement.srcObject = stream;
stream.getVideoTracks()[0].addEventListener('ended', () => {
stopScreenSharing();
});
const shareBtn = document.getElementById('share-screen-btn');
shareBtn.classList.add('active');
shareBtn.innerText = 'Stop Sharing';
captureScreenshot();
console.log('Screen sharing started');
})
.catch(error => {
console.error('Error sharing screen:', error);
alert('Error sharing screen: ' + error.message);
});
}
function stopScreenSharing() {
if (sharedStream) {
sharedStream.getTracks().forEach(track => track.stop());
sharedStream = null;
videoElement.srcObject = null;
const shareBtn = document.getElementById('share-screen-btn');
shareBtn.classList.remove('active');
shareBtn.innerText = 'Share Screen';
console.log('Screen sharing stopped');
}
}
function captureScreenshot() {
return new Promise((resolve, reject) => {
if (!sharedStream) {
alert('Please share your screen first by clicking the "Share Screen" button.');
reject('No shared stream');
return;
}
const video = document.getElementById('shared-screen-video');
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(blob => {
if (blob) {
const imgURL = URL.createObjectURL(blob);
lastCapturedImage = blob;
const screenshotDiv = document.createElement('div');
screenshotDiv.classList.add('screenshot');
const imgElement = document.createElement('img');
imgElement.src = imgURL;
imgElement.alt = 'Captured screenshot';
screenshotDiv.appendChild(imgElement);
const imagesSection = document.getElementById('images');
// Optionally, append instead of replacing
imagesSection.innerHTML = '<h2>Captured Image</h2>'; // Reset with header
imagesSection.appendChild(screenshotDiv);
console.log('Screenshot captured and added to Images section');
imgElement.onload = () => {
URL.revokeObjectURL(imgURL);
};
resolve();
} else {
reject('Failed to capture screenshot');
}
}, 'image/png');
});
}
async function analyzeImage(question) {
if (!lastCapturedImage) {
addMessageToChat('AI', 'No image captured. Please share your screen and try again.');
return;
}
const base64Image = await blobToBase64(lastCapturedImage);
const requestBody = {
prompt: `Answer this question about the image: ${question}`,
images: [{
data: base64Image.split(',')[1],
mime_type: "image/png"
}]
};
try {
// Display loader
const loadingMessage = addMessageToChat('AI', 'Analyzing image...', true);
const response = await fetch(`${GEMINI_API_URL}?key=${GEMINI_API_KEY}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
// Remove loader
removeMessageFromChat(loadingMessage);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Gemini API error: ${response.status} - ${errorText}`);
}
const data = await response.json();
if (data.candidates && data.candidates[0].content && data.candidates[0].content) {
const aiResponse = data.candidates[0].content;
addMessageToChat('AI', aiResponse);
} else {
throw new Error('Unexpected response structure from Gemini API');
}
} catch (error) {
console.error('Error analyzing image with Gemini:', error);
addMessageToChat('AI', 'An error occurred while analyzing the image.');
}
}
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
function addMessageToChat(sender, message, isLoading = false) {
const chatContainer = document.getElementById('chat-container');
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message', sender.toLowerCase() + '-message');
messageElement.textContent = message;
if (isLoading) {
const loader = document.createElement('div');
loader.classList.add('loader');
messageElement.appendChild(loader);
}
chatContainer.appendChild(messageElement);
chatContainer.scrollTop = chatContainer.scrollHeight;
return messageElement;
}
function removeMessageFromChat(messageElement) {
if (messageElement && messageElement.parentNode) {
messageElement.parentNode.removeChild(messageElement);
}
}
document.getElementById('send-btn').addEventListener('click', async () => {
const userInput = document.getElementById('user-input');
const question = userInput.value.trim();
if (question) {
addMessageToChat('User', question);
userInput.value = '';
try {
// Capture screenshot before analyzing
await captureScreenshot();
// Analyze the newly captured image
analyzeImage(question);
} catch (error) {
console.error('Error capturing screenshot:', error);
addMessageToChat('AI', 'An error occurred while capturing the screenshot.');
}
}
});
document.getElementById('user-input').addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent form submission or default behavior
document.getElementById('send-btn').click();
}
});
document.getElementById('share-screen-btn').addEventListener('click', shareScreen);
</script>
</body>
</html>
Key Changes and Additions Explained
-
Asynchronous Screenshot Capture on Send:
- Modification in the Send Button Handler:
- Changed the click event handler for the Send button to an asynchronous function.
- Before analyzing the image, it now captures a screenshot by calling
captureScreenshot().
- After successfully capturing the screenshot, it proceeds to analyze the image with the provided question.
- Added error handling to notify the user if the screenshot capture fails.
document.getElementById('send-btn').addEventListener('click', async () => {
const userInput = document.getElementById('user-input');
const question = userInput.value.trim();
if (question) {
addMessageToChat('User', question);
userInput.value = '';
try {
// Capture screenshot before analyzing
await captureScreenshot();
// Analyze the newly captured image
analyzeImage(question);
} catch (error) {
console.error('Error capturing screenshot:', error);
addMessageToChat('AI', 'An error occurred while capturing the screenshot.');
}
}
});
-
Returning a Promise in captureScreenshot:
- Modified the
captureScreenshot function to return a Promise. This allows the sending function to await the screenshot capture before proceeding.
function captureScreenshot() {
return new Promise((resolve, reject) => {
if (!sharedStream) {
alert('Please share your screen first by clicking the "Share Screen" button.');
reject('No shared stream');
return;
}
// ... existing screenshot capture logic ...
if (blob) {
// ... existing image handling logic ...
resolve();
} else {
reject('Failed to capture screenshot');
}
});
}
-
Preventing Default Behavior on Enter Key:
- In the Enter key handler, added
e.preventDefault(); to prevent any unintended default behavior (like form submission) when the user presses Enter.
document.getElementById('user-input').addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent form submission or default behavior
document.getElementById('send-btn').click();
}
});
-
Updating the Images Section:
- Every time a screenshot is captured (either initially or upon sending a question), the section is updated with the latest screenshot. This ensures that users always see the most recent screenshot corresponding to their question.
Workflow Overview
-
Sharing the Screen:
- When the user clicks the "Share Screen" button, the browser prompts them to select a screen or window to share.
- Upon successful sharing, an initial screenshot is captured and displayed in the "Captured Image" section.
-
Sending a Question:
- The user types a question into the input field and presses Enter or clicks the Send button.
- The input is added to the chat as a User message.
- Before analyzing the image:
- A new screenshot of the shared screen is captured.
- This ensures that the analysis is based on the most recent state of the shared screen.
- The screenshot is displayed in the "Captured Image" section.
- The image along with the question is sent to the Gemini API for analysis.
- The AI's response is then added to the chat.
Additional Considerations
-
API Key Security:
- Important: Ensure that your Gemini API key (
GEMINI_API_KEY) is kept secure. Exposing API keys in client-side code can lead to unauthorized usage. Consider implementing server-side proxies or other security measures to protect your API key.
-
Error Handling:
- The updated code includes basic error handling for both screenshot capture and API analysis. Depending on your application's requirements, you might want to enhance these mechanisms to provide more detailed feedback to the user.
-
Performance:
- Frequent screenshot captures, especially at high resolutions, can be resource-intensive. Ensure that this behavior aligns with the performance expectations of your target user base.
-
Browser Compatibility:
- The
getDisplayMedia API is widely supported in modern browsers, but it's always a good idea to check compatibility and provide fallbacks or warnings for unsupported browsers.
Feel free to integrate this updated code into your project. If you encounter any issues or have further questions, don't hesitate to ask!