Skip to content

Instantly share code, notes, and snippets.

@TotallyNotChase
Last active August 7, 2024 05:26
Show Gist options
  • Save TotallyNotChase/c747c55d4a965954f49a7fa5c3f344e0 to your computer and use it in GitHub Desktop.
Save TotallyNotChase/c747c55d4a965954f49a7fa5c3f344e0 to your computer and use it in GitHub Desktop.
Native Messaging - Rust
{
"name": "pingpong",
"description": "Native messaging host example",
"path": "path/to/release_executable",
"type": "stdio",
"allowed_origins": [
"chrome-extension://extension_id/"
]
}
var start;
/*
On a click on the browser action, send the app a message.
*/
chrome.browserAction.onClicked.addListener(() => {
console.log('Sending: ping')
start = performance.now();
chrome.runtime.sendNativeMessage("pingpong", {text: "ping"}, onResponse);
});
function onResponse(res) {
let end = performance.now();
console.log(`Received: ${res.msg}, Took: ${end - start} ms`);
}
use std::io::{self, Read, Write};
fn main() {
read_input().unwrap();
write_output("{\"msg\":\"pang\"}").unwrap();
}
pub fn read_input() -> io::Result<Vec<u8>> {
let mut instream = io::stdin();
let mut length = [0; 4];
instream.read(&mut length)?;
let mut buffer = vec![0; u32::from_ne_bytes(length) as usize];
instream.read_exact(&mut buffer)?;
Ok(buffer)
}
pub fn write_output(msg: &str) -> io::Result<()> {
let mut outstream = io::stdout();
let len = msg.len();
if len > 1024 * 1024 {
panic!("Message was too large, length: {}", len)
}
outstream.write(&len.to_ne_bytes())?;
outstream.write_all(msg.as_bytes())?;
outstream.flush()?;
Ok(())
}
{
"name": "Native Messaging Example",
"version": "1.0",
"manifest_version": 2,
"description": "Send a message to a native application.",
"background": {
"scripts": ["main.js"]
},
"browser_action": {
"default_icon": "message.svg"
},
"permissions": [
"nativeMessaging"
]
}
@guest271314
Copy link

On Chromium 129

The sender sent an invalid JSON message; message ignored.

{message: 'Error when communicating with the native messaging host.'}

How to echo the input?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment