dellweb3's picture
Deploy verified conversational workbench and isolated Java application previews
5ca3c16 verified
Raw History Blame Contribute Delete
1.31 kB
// One registration per document: duplicated tabs must have distinct identities.
export async function watchPreview(lease,csrf,url){
const bytes=crypto.getRandomValues(new Uint8Array(16));
const client=Array.from(bytes,b=>b.toString(16).padStart(2,'0')).join('');
let attached=false,ended=false,timer;
const send=async(event,keepalive=false)=>{
const response=await fetch(url,{method:'POST',credentials:'same-origin',keepalive,
headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},
body:JSON.stringify({preview_id:lease,client_id:client,event})});
if(!response.ok)throw Error('本次预览已结束,请从工作台重新打开。');
};
const attach=async()=>{await send('attach');attached=true;};
const release=()=>{ended=true;clearInterval(timer);if(attached){attached=false;void send('release',true).catch(()=>{});}};
// Register before the initial request so a quick window close cannot leak a client.
addEventListener('pagehide',release);
await attach();
if(ended){release();return;}
const heartbeat=()=>{if(attached)void send('heartbeat').catch(()=>{});};
const startTimer=()=>{clearInterval(timer);timer=setInterval(heartbeat,15000);};
addEventListener('pageshow',event=>{if(event.persisted){ended=false;void attach().then(startTimer).catch(()=>{});}});
startTimer();
}