【问题标题】:How to receive data in Electron app from protocol link如何从协议链接接收电子应用程序中的数据
【发布时间】:2020-04-19 04:03:04
【问题描述】:

我正在制作一个游戏客户端,我拥有它,您可以在其中从浏览器启动游戏,例如“mygame://whatever”。我正在做一些调试,我希望它显示“收到此数据:随便”。它确实启动了应用程序,但它只是在数据框中显示未定义。我该如何解决这个问题?

main.js:

const {app, BrowserWindow} = require('electron');

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
  mainWindow.loadFile('index.html');
}

app.on('ready', createWindow);

var link;

app.on('open-url', function (event, data) {
  event.preventDefault();
  link = data;
});

app.setAsDefaultProtocolClient('mygame');

// Export so you can access it from the renderer thread
module.exports.getLink = () => link;

index.html:

<!DOCTYPE html>
<html>
  <body>
    <p>Received this data <input id="data"></p>
    <script>
      const {getLink} = require('electron').remote.require('./main.js');
      document.querySelector('#data').value = getLink();
    </script>
  </body>
</html>

package.json:

{
  "name": "mygame",
  "version": "1.0.0-dev",
  "description": "Development copy.",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "dist": "electron-builder"
  },
  "author": "Me",
  "build": {
    "protocols": {
      "name": "mygame-protocol",
      "schemes": [
        "mygame"
      ]
    }
  },
  "devDependencies": {
    "electron": "^6.0.9",
    "electron-builder": "^21.2.0"
  }
}

感谢所有帮助!

【问题讨论】:

    标签: javascript html electron


    【解决方案1】:

    此代码仅适用于 iOS

    app.on('open-url', function (event, data) {
        event.preventDefault();
        link = data;
    });
    

    在win32中你必须使用那个代码

    process.argv[1]
    

    所以您可以像这样在 createWindow() 中添加该代码:

    function createWindow () {
        // Crea la finestra del browser
        let win = new BrowserWindow({
            width: 800,
            height: 600,
        });
    
        //other stuff
    
        link = process.argv[1];
    }
    

    可能有用的资源

    【讨论】:

      猜你喜欢
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2023-03-14
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多