我正在尝试为 Chrome 创建一个简单的串行端口读取器。没什么大不了的,只是接收输入,以便我可以解析它。我遇到一些问题,jQuery 在某一时刻工作,但接下来两行是“$ undefined”。
list :
{ "name": "Serial Reader", "description": "Read Serial barcode scanners with Google Chrome.", "version": "0.1", "manifest_version": 2, "app": { "background": { "scripts": ["background.js", "script.js", "jquery.js"], "transient": true } }, "permissions": [ "serial" ], "icons": { "16": "icon-16.png", "128": "icon-128.png" } }
Script.js:
var onGetDevices = function(ports) { for (var i=0; iNo ports were found."); } else { //Works $("#portList").append("" + ports[i].path + ""); } } }; chrome.serial.getDevices(onGetDevices); var connectionId = -1; var portSelected = $("#portList").val(); //Returns undefined $ var connectCallback = function() { console.log("Connected") }; chrome.serial.connect(portSelected, null , connectCallback); var stringReceived = ''; var onReceiveCallback = function(info) { if (info.connectionId == expectedConnectionId && info.data) { var str = convertArrayBufferToString(info.data); if (str.charAt(str.length-1) === '\n') { stringReceived += str.substring(0, str.length-1); $('#member').val(onLineReceived(stringReceived)); stringReceived = ''; } else { stringReceived += str; } } }; chrome.serial.onReceive.addListener(onReceiveCallback);
Background.js:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('window.html', {
'bounds': {
'width': 1024,
'height': 768
},
"resizable": false
});
});
窗口.html:
<!DOCTYPE html>
<html>
<head>
<title>Serial Reader</title>
<script type="text/JavaScript" src="jquery.js"></script>
<style>
body {
background-image: url(/images/checkin_green.png);
}
</style>
</head>
<body>
<center><strong style="font-size: 16px;">Account Number:</strong> <input id="member" /></center>
<br /><br /><br />
<center><strong style="font-size: 16px;">Avaliable Ports:</strong> <select id="portList"></select></center>
<br />
<center><span id="notFound"></span></center>
<script type="text/JavaScript" src="script.js"></script>
</body>
</html>
我已经研究这个问题很长一段时间了,但无法想出解决方案。我不明白它如何填充端口列表,但接下来的三行表示它未定义。任何帮助将不胜感激!谢谢!
最佳答案
我认为问题在于当您查询#portList
时,DOM尚未完全准备好,因此它返回一个空列表,并且您试图设置不存在的元素的值还没有。
我怀疑 onGetDevices
在 DOM 准备好后被调用,所以没有问题。考虑将 DOM 相关代码包装在 $(document).ready(function(){ ... })
另一个问题可能是您没有查询扩展程序的 DOM,而是查询触发扩展程序的任何页面的 DOM。
关于javascript - jQuery 仅适用于 Chrome 应用程序的某些区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24940770/