Linus
Linus

Reputation: 4783

Passing arguments to a running electron app

I have found some search results about using app.makeSingleInstance and using CLI arguments, but it seems that the command has been removed.

Is there any other way to send a string to an already started electron app?

Upvotes: 2

Views: 519

Answers (2)

Linus
Linus

Reputation: 4783

Ultimately, the most elegant solution to my particular problem was to add a http api endpoint for the Electron app using koa.

const Koa = require("koa");
const koa = new Koa();

let mainWindow;

function createWindow() {
  let startServer = function() {
    koa.use(async ctx => {
        mainWindow.show();
        console.log("text received", ctx.request.query.text);
        ctx.body = ctx.request.query.text;
    });

    koa.listen(3456);
  };
}

Now I can easily send texts to Electron from outside the app using the following url:

localhost:3456?text=myText

Upvotes: 1

pushkin
pushkin

Reputation: 10209

One strategy is to have your external program write to a file that your electron app knows about. Then, your electron app can listen for changes to that file and can read it to get the string:

import fs

fs.watch("shared/path.txt", { persistent: false }, (eventType: string, fileName: string) => {
    if (eventType === "change") {
        const myString: string = fs.readFileSync(fileName, { encoding: "utf8" });
    }
});

I used the synchronous readFileSync for simplicity, but you might want to consider the async version.

Second, you'll need to consider the case where this external app is writing so quickly that maybe the fs.watch callback is triggered only once for two writes. Could you miss a change?

Otherwise, I don't believe there's an Electron-native way of getting this information from an external app. If you were able to start the external app from your Electron app, then you could just do cp.spawn(...) and use its stdout pipe to listen for messages.

If shared memory were a thing in Node, then you could use that, but unfortunately it's not.

Upvotes: 1

Related Questions