File size: 1,314 Bytes
5ca3c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 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();
}