I am trying to capture a screenshot through my app. It works correctly for the 'Entire Screen' option, but for anything selected in the window or Chrome Tab, then the focus doesn't return to my tab after a screenshot.
const handleCameraClick = async (e) => {
try {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: {
cursor: 'always',
displaySurface: 'window',
},
audio: false,
});
const video = document.createElement('video');
video.srcObject = stream;
video.onloadedmetadata = () => {
video.play();
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);
stream.getTracks().forEach((track) => track.stop());
video.srcObject = null;
canvas.toBlob((blob) => {
const file = new File([blob], 'screenshot.png', {
type: 'image/png',
});
setFiles([file]); // setting state in react
}, 'image/png');
};
} catch (err) {
console.error('error capturing screen:', err);
}
};
FYI: claude.ai has the same functionality and it works there.
Can you help me achieve that?
I am trying to capture a screenshot through my app. It works correctly for the 'Entire Screen' option, but for anything selected in the window or Chrome Tab, then the focus doesn't return to my tab after a screenshot.
const handleCameraClick = async (e) => {
try {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: {
cursor: 'always',
displaySurface: 'window',
},
audio: false,
});
const video = document.createElement('video');
video.srcObject = stream;
video.onloadedmetadata = () => {
video.play();
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);
stream.getTracks().forEach((track) => track.stop());
video.srcObject = null;
canvas.toBlob((blob) => {
const file = new File([blob], 'screenshot.png', {
type: 'image/png',
});
setFiles([file]); // setting state in react
}, 'image/png');
};
} catch (err) {
console.error('error capturing screen:', err);
}
};
FYI: claude.ai has the same functionality and it works there.
Can you help me achieve that?
Share Improve this question edited Mar 13 at 10:49 maverickosama92 asked Mar 3 at 9:40 maverickosama92maverickosama92 2,7252 gold badges22 silver badges37 bronze badges1 Answer
Reset to default 0Found this and fixed it: https://developer.mozilla./en-US/docs/Web/API/CaptureController
Code:
const controller = new CaptureController();
stream = await navigator.mediaDevices.getDisplayMedia({
video: {
cursor: 'always',
displaySurface: 'window',
},
audio: false,
selfBrowserSurface: 'exclude',
controller, // attach the controller for conditional focus
});
try {
controller.setFocusBehavior('no-focus-change');
} catch (error) {
console.log("not a tab or window, can't set focus behavior");
}
.... rest of code.