How to launch my electron app from a website

后端 未结 1 408
暖寄归人
暖寄归人 2020-12-23 12:08

We have an electron crypto app that signs transactions (among other things).

We want other websites to have the ability to have a button that opens that electron app

1条回答
  •  醉梦人生
    2020-12-23 12:54

    Since this may be relevant to what I’m doing at work, I decided to give it a go. I’ve only tested this on OSX though!

    I looked at the documentation for app.setAsDefaultProtocolClient and it says this:

    Note: On macOS, you can only register protocols that have been added to your app's info.plist, which can not be modified at runtime. You can however change the file with a simple text editor or script during build time. Please refer to Apple's documentation for details.

    These protocols can be defined when packaging your app with electron-builder. See build:

    {
      "name": "foobar",
      "version": "1.0.0",
      "main": "main.js",
      "scripts": {
        "start": "electron .",
        "dist": "electron-builder"
      },
      "devDependencies": {
        "electron": "^3.0.7",
        "electron-builder": "^20.38.2"
      },
      "dependencies": {},
      "build": {
        "appId": "foobar.id",
        "mac": {
          "category": "foo.bar.category"
        },
        "protocols": {
          "name": "foobar-protocol",
          "schemes": [
            "foobar"
          ]
        }
      }
    }
    

    In your main thread:

    const {app, BrowserWindow} = require('electron');
    
    let mainWindow;
    
    function createWindow () {
      mainWindow = new BrowserWindow({width: 800, height: 600})
      mainWindow.loadFile('index.html');
    }
    
    app.on('ready', createWindow);
    
    var link;
    
    // This will catch clicks on links such as open in foobar
    app.on('open-url', function (event, data) {
      event.preventDefault();
      link = data;
    });
    
    app.setAsDefaultProtocolClient('foobar');
    
    // Export so you can access it from the renderer thread
    module.exports.getLink = () => link;
    

    In your renderer thread:

    Notice the use of the remote API to access the getLink function exported in the main thread

    
    
      
        

    Received this data

    Example

    open in foobar
    

    This also allows you to launch from the command line:

    open "foobar://xyz=1"
    

    How do you get back to the original caller?

    I suppose that when you launch the app you could include the caller url:

    
                                                            
0 讨论(0)
提交回复
热议问题