3

I am trying to communicate with a Samsung J7 over Web using WebUSB API. I am currently using this basic code:

<body>
    <button onclick="myFunction()">Click me</button>
    <script>
        function myFunction() {
        console.log('Clicked');
        var device;
        navigator.usb.requestDevice({ filters: [{ vendorId: 0x04e8 }] })
        .then(selectedDevice => {
                device = selectedDevice;
                console.log('Deive Selected: ');
                console.log(device.productName);
                console.log(device.manufacturerName);
                return device.open(); // Begin a session.
            })
            .catch(error => { console.log(error); });
        }
    </script>
</body>

The device.open() call is returning

DOMException: The device was disconnected

I tested the code on Windows and Ubuntu machines with Chrome. Both gave the same result. Any help with the cause of the problem?

Derlin
  • 9,572
  • 2
  • 32
  • 53

1 Answers1

4

Try hosting your website locally if you are not already doing so. I was getting the same error message when accessing my test page with a file:// url. Hosting the files locally and accessing them from a http:// domain fixed this for me.

A simple way to host the files locally is to run this command from the root directory of your website: python2 -m SimpleHTTPServer. You should then be able to access the site in your browser from the domain http://localhost:8000.

ᅟᅟᅟ
  • 133
  • 6
  • The solution worked great! I was wondering if you knew why it worked or what made you try this? – Mohamad Ali Mhaidly Jan 22 '18 at 16:46
  • @MohamadAliMhaidly I was stuck and someone suggested it to me. I'm not 100% sure why it is necessary to run from a hosted site. My best guess is that it is carried over from earlier versions of the specification. In the old version, the device provided a static set of trusted domains to the browser. These domains could only be HTTP, or HTTPS. In current versions of the specification, only HTTP and HTTPS domains are support by the low level USB requests. [See here](https://wicg.github.io/webusb/#url-descriptor) – ᅟᅟᅟ Jan 23 '18 at 09:08