谷歌Chrome扩展:网站上的串口

9
我使用chrome.serial与COM端口上的设备进行通信,并需要为我的网站上的JavaScript提供基本API。第一次尝试是使用content_script + messaging,但我无法在content_script中使用serial权限,因为其中一个要求扩展程序为打包应用程序,另一个要求为扩展程序。我能解决这个问题吗?
3个回答

11

1
这正是我想避免的:使用两个扩展名而不是一个。但如果这是唯一的方法,我会这样做。谢谢!但似乎我无法在打包的应用程序中使用 chrome.extension,它是 undefined - striker
1
经过一些调查,这是在Chrome中完成它的唯一方法。您必须创建一个应用程序和扩展程序。扩展程序仅包含一个content_script,在那里,一些侦听器(我放置了一个EventListener)将通过chrome.runtime.sendMessage将接收到的数据转发到应用程序。应用程序将使用chrome.runtime.onMessageExternal侦听器等待数据,并在数据到达时打开串口并发送数据。 我必须说,在Linux中,该应用程序运行良好,但在Windows中,有时端口无响应:S 我正在调试此问题,并且解决后,计划上传到github;) - sucotronic
@sucotronic 谢谢您的回答。好的,很明显在 Windows 平台上不稳定。 - sdespont
@sucotronic 我有一种感觉这不是真的。一个应用程序可以从网站进行"externally_connectable"设置,因此不需要内容脚本/扩展程序,只要在之前在清单中设置好,网站就可以直接与应用程序通信。 - Xan
@sucotronic 扩展程序无法直接与串口通信,您需要使用 Chrome 应用程序。考虑到这一点,我认为您不需要该扩展程序。 - Xan
显示剩余3条评论

1

-1

index.html

<button>Connect</button>
<script src="main.js"></script>

main.js

var connectionId;

/* Converts a string to UTF-8 encoding in a Uint8Array; returns the array */

var str2ab = function(str) {
   var encodedString = unescape(encodeURIComponent(str));
   var bytes = new Uint8Array(encodedString.length);
   for (var i = 0; i < encodedString.length; ++i) {
      bytes[i] = encodedString.charCodeAt(i);
   }
   return bytes.buffer;
};

var options = {
  'bitrate': 115200,
  'dataBits': 'eight',
  'parityBit': 'no',
  'stopBits': 'one'
}

document.addEventListener('DOMContentLoaded', function () {
  document.querySelector('button').addEventListener('click', btnSend);
  chrome.serial.connect('COM3', options, function(info) {
    connectionId = info.connectionId;
    console.log("Connection established.");
  });
});

var btnSend = function() {
  var msg = "hello printer 123456\n";
  chrome.serial.send(connectionId, str2ab(msg), function() {} );
}

manifest.json

{
  "name": "Printer at COM3 test",
  "version": "1",
  "manifest_version": 2,
  "permissions": ["serial"],
  "minimum_chrome_version": "23",
  "icons": {
    "16": "icon_16.png",
    "128": "icon_128.png"
  },
  "app": {
    "background": {
      "scripts": ["launch.js"]
    }
  }
}

launch.js

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', {
    id: "mainwin",
    innerBounds: {
      width: 320,
      height: 240
    }
  });
});

这不是网页上的内容,而是一个 Chrome 应用程序(不是问题的答案)。我尝试运行它,为此,请阅读第 4 步:https://developer.chrome.com/webstore/get_started_simple - Veda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接