使用Electron(macOS)打开应用并通过深层链接传递参数 [英] Open app and pass parameters with deep linking using Electron (macOS)

查看:790
本文介绍了使用Electron(macOS)打开应用并通过深层链接传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开应用程序并使用Electron(macOS)进行具有深层链接的参数.

I want to open app and pass parameters with deep linking using Electron (macOS).

项目"electron-deep-linking-mac-win"在GitHub上.

根据"electron-builder"快速设置进行了编辑package.json -guide 生成Mac安装程序:

Edited package.json, following ‘electron-builder’ quick-setup-guide to produce mac installer:

{
  "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'事件并记录参数:


Edited main.js, appended code to register myapp url scheme protocol, listen 'open-url' events and log the arguments:

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}")`)
    }
}


栩栩如生的步骤:-)


Steps to come to life:-)

# 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)后,我尝试打开具有深层链接的electronic-deep-linking-os应用程序,在Safari地址栏中输入myapp://param.

After running the installer (electron-deep-linking-mac-win/dist/electron-quick-start-1.0.0.dmg), i try to open electron-deep-linking-os app with deep linking, entering myapp://param at Safari address bar.

  1. 如果打开了应用程序,它将激活,我可以看到对话框和日志open-url event: myapp://param

如果应用已关闭,则会打开,并显示带有正确网址的对话框,但不会登录到开发控制台!

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

Why with dialog module url is showing properly, but isn't logged to dev console? How to log it?

仅使用 electron-builder (使用electron-packager )!

推荐答案

为macOS和win32解决(更新项目'electron-deep-linking -mac-win"(在GitHub上).


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代码说明:

  • let deeplinkingUrl,我们保留提供的网址.

  • At let deeplinkingUrl we keep the provided url.

在macOS上,您需要监听app.open-url事件,而在Windows上,URL应该在process.argv中(在主进程中)可用.

  • 在macOS平台上,此捕获在 'open-url'事件,我们将其设置为deeplinkingUrl = url! (请参见// Protocol handler for osx)

在win32平台上,此文件与process.argv 一起保存在其他论点.要仅获取提供的URL,请deeplinkingUrl = argv.slice(1). (请参见// Protocol handler for win32)

On win32 platform this is saved at process.argv together with other arguments. To get only the provided url, deeplinkingUrl = argv.slice(1). (See // Protocol handler for win32)

app.makeSingleInstance方法中,我们检查平台,我们相应地设置deeplinkingUrl!如果我们在Win32平台上,则该URL位于回调的argv变量中,否则应已在macOS上的'open-url'事件中设置了该URL! (请参见// Force Single Instance Application)

At app.makeSingleInstance method we check in which platform we are and we set deeplinkingUrl accordingly! If we are on win32 platform, the url is located at argv variable from callback, else on macOS should have already been set at 'open-url' event! (See // Force Single Instance Application)

这篇关于使用Electron(macOS)打开应用并通过深层链接传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆