使用Electron(macOS),通过深度链接打开应用并传递参数

28
我希望使用Electron(macOS)打开应用程序并通过深度链接传递参数。 项目'electron-deep-linking-mac-win'在GitHub上
编辑package.json,按照'electron-builder'快速设置指南生成mac安装程序。请参考下面的动画演示:

enter image description here

{
  "name": "electron-deep-linking-osx",
  "version": "1.0.0",
  "description": "A minimal Electron application with Deep Linking (OSX)",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "pack": "build --dir",
    "dist": "build"
  },
  "repository": "https://github.com/oikonomopo/electron-deep-linking-osx",
  "keywords": [
    "Electron",
    "osx",
    "deep-linking"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "1.6.6",
    "electron-builder": "17.1.2"
  },
  "build": {
    "appId": "your.id",
    "mac": {
      "category": "your.app.category.type"
    },
    "protocols": {
      "name": "myApp",
      "schemes": ["myApp"]
    }
  }
}

编辑了 main.js,向注册myapp URL协议方案添加了代码,监听'open-url'事件并记录参数:

const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
// Module with utilities for working with file and directory paths.
const path = require('path')
// Module with utilities for URL resolution and parsing.
const url = require('url')
// Module to display native system dialogs for opening and saving files, alerting, etc.
const dialog = electron.dialog

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

// The setAsDefaultProtocolClient only works on packaged versions of the application
app.setAsDefaultProtocolClient('myApp')

// Protocol handler for osx
app.on('open-url', function (event, url) {
  event.preventDefault();
  log("open-url event: " + url)

  dialog.showErrorBox('open-url', `You arrived from: ${url}`)
})

// Log both at terminal and at browser
function log(s) {
    console.log(s)
    if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
    }
}

实现方法:-)

# Clone this repository
git clone https://github.com/oikonomopo/electron-deep-linking-mac-win.git
# Go into the repository
cd electron-deep-linking-mac-win
# Install dependencies
npm install
# Run the app
npm start
# Produce installer
npm run dist

安装程序后(electron-deep-linking-mac-win/dist/electron-quick-start-1.0.0.dmg),我尝试使用深度链接在Safari地址栏中输入myapp://param来打开electron-deep-linking-os应用程序。

  1. 如果应用程序已打开,则会激活并显示对话框和日志open-url event: myapp://param

  2. 如果应用程序已关闭,则会打开,显示具有正确URL的对话框,但不会记录到开发控制台中!

为什么使用dialog模块url正确显示,但未记录到开发控制台中?如何记录它?

寻找仅使用electron-builder使用electron-packager)的解决方案!


在Windows上,我已经实现了相同的功能!我希望有更简单的解决方案,最好只使用 "electron-builder"。 - oikonomopo
1
可能的指示:
  1. https://discuss.atom.io/t/custom-protocol-and-closed-app/37030
  2. https://github.com/masahirompp/electron-open-url-sample
  3. https://github.com/electron/electron/issues/3847
- oikonomopo
更新Info.plist不是Mac应用程序必须的吗?您在哪里更新Info.plist? - Pramod
这里可能存在一个问题,因为您在初始声明let mainWindow时将其初始化为undefined,但是您继续将其与null进行比较。我建议您从一开始就将其设置为null,或者在需要的任何地方都将其与undefined进行比较。 - Azeez Olaniran
2个回答

18

解决了macOS和win32的问题(在GitHub上更新了项目'electron-deep-linking-mac-win')。


package.json

{
  "name": "electron-deeplinking-macos-win32",
  "version": "0.0.1",
  "description": "Minimal Electron application with deep inking (macOS/win32)",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "pack": "build --dir",
    "dist": "build"
  },
  "repository": "https://github.com/oikonomopo/electron-deep-linking-osx",
  "author": "oikonomopo",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "1.6.6",
    "electron-builder": "17.1.2"
  },
  "build": {
    "appId": "oikonomopo.electron-deeplinking-macos-win32",
    "protocols": {
      "name": "electron-deep-linking",
      "schemes": ["myapp"]
    },
    "mac": {
      "category": "public.app-category.Reference"
    },
    "win": {
    }
  }
}

main.js:

const {app, BrowserWindow} = require('electron')
// Module with utilities for working with file and directory paths.
const path = require('path')
// Module with utilities for URL resolution and parsing.
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

// Deep linked url
let deeplinkingUrl

// Force Single Instance Application
const shouldQuit = app.makeSingleInstance((argv, workingDirectory) => {
  // Someone tried to run a second instance, we should focus our window.

  // Protocol handler for win32
  // argv: An array of the second instance’s (command line / deep linked) arguments
  if (process.platform == 'win32') {
    // Keep only command line / deep linked arguments
    deeplinkingUrl = argv.slice(1)
  }
  logEverywhere("app.makeSingleInstance# " + deeplinkingUrl)

  if (win) {
    if (win.isMinimized()) win.restore()
        win.focus()
  }
})
if (shouldQuit) {
    app.quit()
    return
}

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Protocol handler for win32
  if (process.platform == 'win32') {
    // Keep only command line / deep linked arguments
    deeplinkingUrl = process.argv.slice(1)
  }
  logEverywhere("createWindow# " + deeplinkingUrl)

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// Define custom protocol handler. 
// Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('myapp')

// Protocol handler for osx
app.on('open-url', function (event, url) {
  event.preventDefault()
  deeplinkingUrl = url
  logEverywhere("open-url# " + deeplinkingUrl)
})

// Log both at dev console and at running node console instance
function logEverywhere(s) {
    console.log(s)
    if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
    }
}

main.js 代码说明:


2
这在Mac上运行良好,但在Linux上不起作用。我需要为Linux进行特定的设置吗?是否有任何方法可以检查应用程序是否使用深度链接打开,或者当我点击具有深度链接URL的按钮时是否会触发某些操作?类似于Linux的open-url之类的东西? - Bhaskar Dabhi
1
makeSingleInstance现已弃用。 - mix3d

5
你应该在will-finish-launching回调中设置open-url事件如文档所述。我之前也遇到过类似的open-file问题,直到我在will-finish-launching回调中设置它时才解决了。
你可以在你提供的示例中看到他们是这样做的。
尽管它在will-finish-launching下提到了这一点,但实际上它也应该在open-urlopen-file文档中提到,因为很容易被忽略。
app.on('will-finish-launching', () => {
  // Protocol handler for osx
  app.on('open-url', (event, url) => {
    event.preventDefault();
    log("open-url event: " + url)
  })
});

尝试过了,但没有解决问题。只有在应用程序已打开时,它才会再次捕获URL! - oikonomopo
1
更新:我已经更新了代码等内容。现在我可以看到带有URL的对话框,但是一开始无法记录它。之后,我可以同时在对话框中看到URL和在开发控制台中记录日志!有什么想法吗? - oikonomopo
目前的代码看起来似乎不需要在“will-finish-launching”下提及“open-url”! - oikonomopo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接