我在通过 angularJS 为 chrome 使用 WebUSB API 时遇到问题。这是一个项目,我需要访问 esc/pos 热敏打印机来打印发票。
在普通的 JavaScript 中:
HTML:
<button id="connect">Connect</button>
Javascript:
document.addEventListener('DOMContentLoaded', async () => {
try{
let devices = await navigator.usb.getDevices({
filters: [{
vendorId: VENDOR_ID,
productId: PRODUCT_ID
}]
});
let button = document.getElementById('connect');
button.addEventListener('click', async () => {
if (devices.length === 0) {
var device;
let devices = [];
try {
device = await navigator.usb.requestDevice({
filters: [{
vendorId: VENDOR_ID,
productId: PRODUCT_ID
}]
});
}
catch (error) {
console.log(error)
}
}
else {
device = devices[0];
}
console.log('open');
await device.open();
console.log('opened:', device);
await device.selectConfiguration(1); // Select configuration #1 for the device.
await device.claimInterface(0); // Request exclusive control over interface #0.
console.log(await device.transferOut(2,buffer));
})
}
catch (error) {
console.log(error)
}
在 angularjs: HTML:
<button class="btn btn-warning" ng-init="newinvscopetest.bindPrint()" id="print">Print</button>
控制器:
newinvscopetest.bindPrint = function (){
let button = document.getElementById('print');
button.addEventListener('click', async () => {
let device;
let devices = [];
const VENDOR_ID = 0x0FE6;
const PRODUCT_ID = 0x811E;
try {
devices = await navigator.usb.getDevices({
filters: [{
vendorId: VENDOR_ID,
productId: PRODUCT_ID
}]
});
if (devices.length === 0) {
try {
device = await navigator.usb.requestDevice({
filters: [{
vendorId: VENDOR_ID,
productId: PRODUCT_ID
}]
});
}
catch (error) {
console.log(error)
}
}
else {
device = devices[0];
}
console.log('open');
await device.open();
console.log('opened:', device);
await device.selectConfiguration(1); // Select configuration #1 for the device.
await device.claimInterface(0); // Request exclusive control over interface #0.
let buffer = newinvscopetest.getPrintData();
console.log(await device.transferOut(2,buffer));
}
catch (error) {
console.log(error)
}
});
};
在尝试使用角度脚本时,DOMException 会引发错误:
必须处理用户手势以显示权限请求。
这是 web usb 的 requestDevice 函数所要求的,它应该是用户按钮单击或鼠标悬停。
这在第一个示例中运行良好,因为用户正在单击按钮来触发该功能。
在第二个例子中,同样的事情正在发生。我什至避免使用 ng-click 让本地事件侦听器尝试是否可行。但也没有运气。
谁能帮我?angularJS 出了什么问题?