I am trying to call a MacOS app written in Objective C from a Browser extension using native messaging.
So far I have come up with this code which handles requests made with chrome.runtime.sendNativeMessage.
int main(int argc, char * argv[]) {
@autoreleasepool {
NSFileHandle *stdIn = [NSFileHandle fileHandleWithStandardInput];
NSError * stdinError = nil;
NSData * rawReqLen = [stdIn readDataUpToLength:4 error:&stdinError];
if(rawReqLen == nil || stdinError != nil) return 1;
NSUInteger reqLen;
[rawReqLen getBytes:&reqLen length:4];
NSData * req = [stdIn readDataUpToLength:reqLen error:&stdinError];
if(stdinError != nil) return 1;
handleRequest(req); // this does something depending on the received request
return 0;
}
}
This is working.
I need help figuring out how to use chrome.connectNative to maintain the connection open. Specifically, my problem is to let the MacOS app keep listening to incoming messages until the port is closed by a call to port.disconnect from the browser extension.
I've tried this code which does not work.
int main(int argc, char * argv[]) {
@autoreleasepool {
NSFileHandle *stdIn = [NSFileHandle fileHandleWithStandardInput];
[[NSNotificationCenter defaultCenter] addObserverForName:NSFileHandleDataAvailableNotification
object:stdIn
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSError * stdinError = nil;
NSData * rawReqLen = [stdIn readDataUpToLength:4 error:&stdinError];
if(rawReqLen == nil || stdinError != nil) exit(1);
NSUInteger reqLen;
[rawReqLen getBytes:&reqLen length:4];
NSData * req = [stdIn readDataUpToLength:reqLen error:&stdinError];
if(stdinError != nil) exit(1);
handleRequest(req);
}];
[stdIn waitForDataInBackgroundAndNotify];
}
}
Does someone know how to achieve this ?