summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/resources/chromium/webusb-child-test.js
blob: 21412f66b0a036e53f79824951c6cad1f152f018 (plain)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';

// This polyfill prepares a child context to be attached to a parent context.
// The parent must call navigator.usb.test.attachToContext() to attach to the
// child context.
(() => {
  if (this.constructor.name === 'DedicatedWorkerGlobalScope' ||
      this !== window.top) {

    // Run Chromium specific set up code.
    if (typeof MojoInterfaceInterceptor !== 'undefined') {
      let messageChannel = new MessageChannel();
      messageChannel.port1.onmessage = async (messageEvent) => {
        if (messageEvent.data.type === 'Attach') {
          messageEvent.data.interfaces.forEach(interfaceName => {
            let interfaceInterceptor =
                new MojoInterfaceInterceptor(interfaceName);
            interfaceInterceptor.oninterfacerequest =
              e => messageChannel.port1.postMessage({
                type: interfaceName,
                handle: e.handle
              }, [e.handle]);
            interfaceInterceptor.start();
          });

          // Wait for a call to GetDevices() to ensure that the interface
          // handles are forwarded to the parent context.
          try {
            await navigator.usb.getDevices();
          } catch (e) {
            // This can happen in case of, for example, testing usb disallowed
            // iframe.
            console.error(`getDevices() throws error: ${e.name}: ${e.message}`);
          }

          messageChannel.port1.postMessage({ type: 'Complete' });
        }
      };

      let message = { type: 'ReadyForAttachment', port: messageChannel.port2 };
      if (typeof Window !== 'undefined')
        parent.postMessage(message, '*', [messageChannel.port2]);
      else
        postMessage(message, [messageChannel.port2]);
    }
  }
})();