striker
striker

Reputation: 1263

Google Chrome Extension serial port on website

I use chrome.serial to communicate with device on COM port and i need provide basic api for javascript on my web-site. First try was with content_script + messaging, but i can't use serial permission with content_script because one of them require extension to be packaged app, and another to be extension. Can i solve this issue?

Upvotes: 9

Views: 18435

Answers (3)

espongha
espongha

Reputation: 225

Update to this thread, they may use Web Serial to communicate using web to serial port.

https://chromestatus.com/feature/6577673212002304
https://web.dev/serial/

Upvotes: 1

Kadir Erturk
Kadir Erturk

Reputation: 601

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
    }
  });
});

Upvotes: -1

Sudarshan
Sudarshan

Reputation: 18524

You can solve this by a chrome extension to support Content Scripts and packaged app for serial port communication with External Message Communication

Fetch your Extension Id's using management API and establish connection for single message communication.

On Message External is fired when a message is sent from another extension.

References

Upvotes: 11

Related Questions