File size: 1,715 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
24
25
26
27
28
29
"""Fixed child-side bridge injected into a sandboxed generated business page."""
import re

BRIDGE='''<script>
(()=>{let serial=0;const pending=new Map();
const bridge=(method,path)=>new Promise((resolve,reject)=>{
 if(!['GET','POST'].includes(method)||typeof path!=='string'||path.length>500){reject(Error('请求格式无效'));return;}
 const id='request-'+(++serial);const timer=setTimeout(()=>{pending.delete(id);reject(Error('请求超时,结果未确认'));},30000);
 pending.set(id,{resolve,reject,timer});parent.postMessage({type:'zk-business-request',id,method,path},'*');
});
Object.defineProperty(window,'__zkBusinessBridge',{value:bridge,writable:false,configurable:false});
window.zkRequest=bridge;
addEventListener('message',event=>{const data=event.data;if(event.source!==parent||!data||data.type!=='zk-business-response')return;
 const entry=pending.get(data.id);if(!entry)return;pending.delete(data.id);clearTimeout(entry.timer);
 if(data.ok)entry.resolve(data.body);else entry.reject(Error(data.error||'操作未完成'));
});})();
</script>'''


def inject(page):
    result,count=re.subn(r'<html\b[^>]*>',lambda match:match.group(0)+BRIDGE,page,count=1,flags=re.I)
    if count!=1:raise ValueError('BUSINESS_PAGE_INVALID')
    # Restore the trusted bridge after generated scripts; a model may accidentally
    # declare a global function with the same name. Onload handlers run afterward.
    restore='<script>window.zkRequest=window.__zkBusinessBridge;</script>'
    result,count=re.subn(r'</body\s*>',lambda match:restore+match.group(0),result,count=1,flags=re.I)
    if not count:result=re.sub(r'</html\s*>',lambda match:restore+match.group(0),result,count=1,flags=re.I)
    return result