webusb-child-test.js (1757B)
1 'use strict'; 2 3 // This polyfill prepares a child context to be attached to a parent context. 4 // The parent must call navigator.usb.test.attachToContext() to attach to the 5 // child context. 6 (() => { 7 if (this.constructor.name === 'DedicatedWorkerGlobalScope' || 8 this !== window.top) { 9 10 // Run Chromium specific set up code. 11 if (typeof MojoInterfaceInterceptor !== 'undefined') { 12 let messageChannel = new MessageChannel(); 13 messageChannel.port1.onmessage = async (messageEvent) => { 14 if (messageEvent.data.type === 'Attach') { 15 messageEvent.data.interfaces.forEach(interfaceName => { 16 let interfaceInterceptor = 17 new MojoInterfaceInterceptor(interfaceName); 18 interfaceInterceptor.oninterfacerequest = 19 e => messageChannel.port1.postMessage({ 20 type: interfaceName, 21 handle: e.handle 22 }, [e.handle]); 23 interfaceInterceptor.start(); 24 }); 25 26 // Wait for a call to GetDevices() to ensure that the interface 27 // handles are forwarded to the parent context. 28 try { 29 await navigator.usb.getDevices(); 30 } catch (e) { 31 // This can happen in case of, for example, testing usb disallowed 32 // iframe. 33 console.error(`getDevices() throws error: ${e.name}: ${e.message}`); 34 } 35 36 messageChannel.port1.postMessage({ type: 'Complete' }); 37 } 38 }; 39 40 let message = { type: 'ReadyForAttachment', port: messageChannel.port2 }; 41 if (typeof Window !== 'undefined') 42 parent.postMessage(message, '*', [messageChannel.port2]); 43 else 44 postMessage(message, [messageChannel.port2]); 45 } 46 } 47 })();