Web Serial Api 浏览器打开串口发送指令读写IC卡 |
|||
发布者:广州荣士电子有限公司 发布时间: 2024-6-25 | |||
出于信息安全的原因,以往浏览器是无法直接控制电脑上的设备的,所以,很多黑客为了控制其他电脑,一般就是做一段木马程序,通过各种办法引诱上网小白们通过浏览器下载安装一堆堆的垃圾软件,其中很有可能就有一段木马病毒通过这种方式植入到了电脑。中了木马病毒的设备就象一只待宰的羔羊,黑客们可以通过木马病毒控制电脑,偷取电脑内的数据、破坏电脑系统。在这种情况下,浏览器做为上网的窗口,如果它可以直接控制电脑上的设备是一件很有安全隐患的事情。 然而,随着互联网的发展,以B/S结构开发程序越来越占主流,B/S结构的软件都通过浏览器与操作人员交互数据,这又使得通过浏览器来控制本电脑的设备变得越来越有需求。 你看,这是不是非常矛盾的一种状态? 但是,需求一定是占主导地位的,需求推动整个世界的前进,所以,通过许多大神的辛勤、努力,开发了一些由浏览器控制电脑设备的工具,Web Serial Api就是其中的一个,它可以通过浏览器直接向电脑上的串口设备发送指令,从而控制通过串口连接的电脑外设。Microsoft Edge、Google Chrome、360等主流浏览器都以全面支持Web Serial Api。 出于安全考虑,浏览器连接串口前,都会跳出提示窗口让使用者确认授权连接指定的串口。 以下Javascript代码展示了通过 Web Serial Api ,浏览器打开指定串口,向串口发送读、写M1卡的指令完成读写M1卡操作。
一、判断浏览器是否支持 web Serial Api
二、Web浏览器选择连接已配对的串口
async function SelectSerial(){ 三、打开串口并设置参数 async function OpenSerial(){if (port==null){ alert('请先选择要操作的串口号!'); return; }else{ var baudSelected = parseInt(document.getElementById("select_btn").value); await port.open({baudRate: baudSelected, }); listenReceived(); alert('串口打开成功!'); } } 四、监听串口数据 async function listenReceived(){if (reading){ console.log("On reading."); return; } reading=true; while (port.readable && reading) { reader = port.readable.getReader(); try { while (true) { const { value, done } = await reader.read(); if (done) {break; } updateInputData(value); } } catch (e) { alert(e); } finally { reader.releaseLock(); } } await port.close(); // 关闭串口 port = null; alert("串口已关闭!"); } 五、关闭已打开的串口 async function CloseSerial(){if ((port == null) || (!port.writable)) { alert("请选择并打开与发卡器相连的串口!"); return; } if (reading) { reading = false; reader?.cancel(); } } 六、向串口发送数据 async function SendData(){if ((port == null) || (!port.writable)) { alert("请选择并打开与发卡器相连的串口!"); return; } var beepdelay=parseInt(document.getElementById("beepdelay").value); const outputData = new Uint8Array(5); outputData[0]=0x03; outputData[1]=0x0f; outputData[2]=beepdelay % 256; outputData[3]=beepdelay / 256; outputData[4]=outputData[1] ^ outputData[2] ^outputData[3]; const writer = port.writable.getWriter(); await writer.write(outputData); // 发送数据 writer.releaseLock(); } |
|||
![]() | 上一篇:NTAG424 DNA安全加密动态NFC | ![]() | 下一篇:C++支持多个客户端同时连接的TCP服务端 |