WebUSB API 會向網路公開非標準的通用序列匯流排 (USB) 相容裝置。本頁說明擴充功能專屬的 API 相關事項。如要瞭解 WebUSB API 的完整詳細資料,請參閱 MDN。
擴充功能適用情形
Chrome 118 以上版本。
權限
不需要任何資訊清單檔案權限,但 WebUSB 會觸發瀏覽器的使用者授權流程。
資訊清單
這個 API 不需要任何資訊清單鍵。
支援情境
這項 API 幾乎可在任何情況下使用,但 WebUSB.requestDevice() 方法無法在擴充功能服務工作人員中使用。詳情請參閱下節。
在擴充功能 Service Worker 中使用這個 API 時,裝置連線工作階段會讓 Service Worker 保持運作。
Chrome 擴充功能差異
雖然擴充功能 Service Worker 可以使用 WebUSB,但擴充功能 Service Worker 無法呼叫 WebUSB.requestDevice(),因為這會傳回以 USBDevice 執行個體解析的 Promise。如要解決這個問題,請從擴充功能服務工作站以外的擴充功能頁面呼叫 requestDevice(),然後將訊息傳送至擴充功能服務工作站。
下列程式碼遵循一般模式,在需要使用者手勢的權限流程中呼叫 requestDevice()。裝置取得後,會將訊息傳送至 Service Worker,後者即可使用 getDevices() 擷取裝置。
popup.js:
myButton.addEventListener("click", async () => {
await navigator.usb.requestDevice({
filters: [{ vendorId: 0x1234, productId: 0x5678 }],
});
chrome.runtime.sendMessage("newDevice");
});
service-worker.js
chrome.runtime.onMessage.addListener(async (message) => {
if (message === "newDevice") {
const devices = await navigator.usb.getDevices();
for (const device of devices) {
// open device connection.
await device.open();
}
}
});