我正在使用WordPress插件中的Html5Qrcode扫描仪来扫描产品条形码。我的工作流程如下:
1.启动Html5Qrcode扫描仪并扫描条形码。
2.使用解码的条形码值在表单中搜索和显示有关产品的信息。
3.在用户更新表单并单击“Submit”之后,进行 AJAX 调用以处理表单数据。
4.成功提交表单后,我希望自动重新启动Html5Qrcode扫描仪,以便用户可以扫描下一个产品。
但是,我无法在提交表单后成功重新启动扫描仪。当使用按钮单击事件手动启动时,扫描仪工作完美。仅当我尝试在 AJAX 成功回调中以编程方式启动扫描程序时,才会出现此问题。
我已经将扫描器启动过程定义为一个单独的JavaScript函数,在按钮单击事件和 AJAX 成功回调中调用该函数。
下面是相关代码的一个片段:
function startScanner() {
// Show the scanner and hide the product info
$('#reader').show();
$('#product_info').hide();
if (qrreader == null) {
qrreader = new Html5Qrcode(qrreaderElementId);
const videoConstraints = {
facingMode: "environment"
};
const config = {
fps: 10,
qrbox: {
width: 250,
height: 250
}
};
let isWaitingForResponse = false;
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
if (isWaitingForResponse) {
console.log("Still waiting for the previous scan...");
return;
}
isWaitingForResponse = true;
console.log(`Message: ${decodedText}, Result: ${JSON.stringify(decodedResult)}`);
$('#barcode_search').val(decodedText); // Set the value of the barcode field
$("#barcode_submit").trigger('click'); // Trigger a click event on the submit button
// Hide the scanner and show the product info
$('#reader').hide();
$('#product_info').show();
// Set a timeout to allow the next scan
setTimeout(() => {
isWaitingForResponse = false;
}, 5000); // 5000ms = 5 seconds, adjust as needed
};
const qrCodeErrorCallback = (errorMessage) => {
console.log(errorMessage);
};
qrreader.start(
videoConstraints,
config,
qrCodeSuccessCallback,
qrCodeErrorCallback
).catch((error) => {
console.log(error);
});
}
}
// Start scanner on button click
$(document).on('click', '#start_reader', function() {
startScanner();
});
// Start scanner after successful form submission
$('#update_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: '../my-scanner-script.php',
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
// Attempt to start the scanner
startScanner();
}
}
});
});
尽管控制台中没有抛出错误,但表单提交后扫描仪不会重新启动。我已经验证了startScanner函数确实在 AJAX 成功回调中被调用。
我怀疑这可能是由于浏览器对自动播放媒体流的限制,而不需要用户直接操作。如果是这种情况,是否有任何变通方法允许扫描仪以编程方式重新启动?
对这个问题的任何帮助或见解将不胜感激。
先谢谢你。
1条答案
按热度按时间lb3vh1jj1#
似乎只有当
global
变量qrreader
问题
如果你再次调用
startScanner
qrreader * 将 * 是一个Object示例,if
语句将不会运行。可能的解决方案:
此外,还有一个潜在的问题,即您没有正确清除超时。清除它们,如:
为了完整起见,这里有一个轻微的改造,使用单个示例,没有任何检查,也没有使用超时: