feat: Enhance exposeInMainWorld exposed attribute
This commit is contained in:
		
							parent
							
								
									d86fa01865
								
							
						
					
					
						commit
						7f6df58801
					
				| 
						 | 
					@ -20,6 +20,24 @@ contextBridge.exposeInMainWorld('bridge', {
 | 
				
			||||||
  __filename,
 | 
					  __filename,
 | 
				
			||||||
  fs,
 | 
					  fs,
 | 
				
			||||||
  path,
 | 
					  path,
 | 
				
			||||||
  ipcRenderer,
 | 
					  ipcRenderer: withPrototype(ipcRenderer),
 | 
				
			||||||
  removeLoading,
 | 
					  removeLoading,
 | 
				
			||||||
})
 | 
					})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it.
 | 
				
			||||||
 | 
					function withPrototype(obj: Record<string, any>) {
 | 
				
			||||||
 | 
					  const protos = Object.entries(Object.getPrototypeOf(obj))
 | 
				
			||||||
 | 
					  for (const [key, value] of protos) {
 | 
				
			||||||
 | 
					    if (!Object.prototype.hasOwnProperty.call(obj, key)) {
 | 
				
			||||||
 | 
					      if (typeof value === 'function') {
 | 
				
			||||||
 | 
					        // Some native API not work Renderer-process, like `NodeJS.EventEmitter['on']`. Wrap a function patch it.
 | 
				
			||||||
 | 
					        obj[key] = function (...args: any) {
 | 
				
			||||||
 | 
					          return value.call(obj, ...args)
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					      } else {
 | 
				
			||||||
 | 
					        Object.assign(obj, { [key]: value })
 | 
				
			||||||
 | 
					      }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					  return obj
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
		Loading…
	
		Reference in New Issue