async iframe cropTarget postmsg
by jib1
HTML
<iframe id="iframe" allow="display-capture"></iframe><br>
<button id="button">Self Capture</button><br>
<div id="div"></div>
<video id="video" width="160" height="120" autoplay muted></video>
JavaScript
const console = { log: msg => div.innerHTML += msg + "<br>" };
async function subframe() {
const origin = "https://fiddle.jshell.net";
try {
const stream = await navigator.mediaDevices.getUserMedia({video: true});
let element;
for (let i=0; i<2; i++) {
// Chrome appears to only allow cropping to divs and iframes atm
const video = document.documentElement.appendChild(document.createElement("video"));
video.width = 160;
video.height = 100;
video.autoplay = true;
video.srcObject = stream;
if (!element) element = video;
}
parent.postMessage("Ready", origin);
await new Promise(r => window.onmessage = r);
parent.postMessage(await navigator.mediaDevices.produceCropId(""), origin);
} catch (e) {
parent.postMessage(`${e.name}: ${e.message}`, origin);
}
}
iframe.srcdoc = `<html\><script\>(${subframe.toString()})();</script\></html\>`;
window.addEventListener("message", ({data: s}) => (typeof s == "string") && console.log(s));
button.onclick = async () => {
try {
const stream = await navigator.mediaDevices.getDisplayMedia();
const base = performance.now();
video.onplay = () => console.log(`Time to play: ${(performance.now() - base).toFixed(2)}`);
video.srcObject = stream;
iframe.contentWindow.postMessage("capturing", "https://fiddle.jshell.net");
const {data: cropTarget} = await new Promise(r => window.onmessage = r);
const [track] = stream.getVideoTracks();
await track.cropTo(cropTarget);
console.log(`Time to crop: ${(performance.now() - base).toFixed(2)}`);
} catch(e) {
console.log(e);
}
};