我在通过WebUSB为chrome使用angularJS 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的requestDevice功能所需要的,它应该是用户按钮单击或鼠标悬停。
在第一个例子中,这很好,因为用户正在单击按钮来触发函数。
在第二个例子中,同样的事情正在发生。我甚至避免了让本地事件侦听器尝试使用ng单击。但这也没什么好运气。
有谁可以帮我?angularJS出了什么问题?
发布于 2018-04-23 15:53:37
我不确定第一个示例,但在第二个示例中,在调用requestDevice()之前,您需要等待getDevices()返回的承诺。这意味着您的异步函数的其余部分将在此承诺得到解决后调用,并且您的代码不再有用户手势。
与每次单击时调用getDevices()不同,我建议只在页面加载时调用它一次,并使用事件侦听器(与navigator.usb.addEventListener('connect', ...)一起添加)检测页面加载后连接的设备。
https://stackoverflow.com/questions/49970485
复制相似问题