javascriptbluetooth-lowenergygattchrome-extension-manifest-v3web-bluetooth

Connecting to bluetooth device using service worker in chrome extension


I'm working on chrome extension using manifest v3 that needs to connect to a bluetooth device (Using the Web Bluetooth API), receive messages from the device, and send the messages to multiple diffrent content scripts.

I already have a working version with a single content script that connects and communicates with the device, but since I need it to connect to multiple diffrent sites I thought i'll switch to using a service worker for bluetooth communication.

currently since I can't open the bluetooth connection dialogue on the service worker I inject a simple connection script to the current active tab and it mangages to connect but I have no way of sending back the bluetooth device object from the injected content script back to the service worker. Is there anyway to make my own bluetooth connection dialogue so the connection will be done through the service worker script? or is there a way to transfer the bluetooth device object from the injected content script to the service worker?

This is the injecting of the function

    if (message.text == "click") {
        
        chrome.tabs.query({active: true,currentWindow: true}, function(tabs) {
        chrome.scripting.executeScript(
        {
          target: {tabId: tabs[0].id},
          func: openConnectionDialog,
        })  
        
        });

This is the injected function

function openConnectionDialog() {
    return navigator.bluetooth.requestDevice({
        filters: [{ namePrefix: 'myDevice' }],
        optionalServices: ['6e400001-b5a3-f393-e0a9-e50e24dcca9e']
    })
    .then(device => {
        console.log(device)
        chrome.runtime.sendMessage({text: "device connected", device: device})          
    });
}

When I listen to the message I get the text message but an empty object for the device since it seems it is not possible to send an object between content scripts and the service worker


Solution

  • Web Bluetooth is not currently supported in Service Workers, including in Extensions. If you file a feature request for this on the Chromium issue tracker it will help us track interest in developing this capability.