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

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

问题描述

我想使用 Electron (macOS) 打开应用程序并通过深度链接传递参数.

编辑 package.json,遵循 'electron-builder 的快速设置指南 制作 mac 安装程序:

<代码>{名称":电子深度链接-osx",版本":1.0.0","description": "带有深度链接 (OSX) 的最小 Electron 应用程序","main": "main.js",脚本":{开始":电子.","pack": "构建 --dir",dist":构建"},存储库":https://github.com/oikonomopo/electron-deep-linking-osx",关键词":[电子","osx",深度链接"],作者":GitHub",许可证":CC0-1.0",开发依赖":{电子":1.6.6",电子制造商":17.1.2"},建造": {"appId": "你的.id",苹果电脑": {类别":your.app.category.type"},协议":{名称":我的应用程序",方案":[我的应用程序"]}}}

<小时>

编辑 main.js,将代码附加到 注册myapp url scheme协议,监听'open-url' 事件 并记录参数:

const electron = require('electron')//控制应用程序生命周期的模块.常量应用程序=电子.app//创建本机浏览器窗口的模块.const BrowserWindow = electron.BrowserWindow//带有用于处理文件和目录路径的实用程序的模块.常量路径 = 要求('路径')//带有用于 URL 解析和解析的实用程序的模块.常量 url = 要求('url')//显示用于打开和保存文件、警报等的本机系统对话框的模块.常量对话框 = electron.dialog//保持窗口对象的全局引用,如果不这样做,窗口将//当 JavaScript 对象被垃圾回收时自动关闭.让主窗口函数创建窗口(){//创建浏览器窗口.mainWindow = new BrowserWindow({width: 800, height: 600})//并加载应用程序的 index.html.mainWindow.loadURL(url.format({路径名:path.join(__dirname, 'index.html'),协议:'文件:',斜线:真}))//打开开发工具.mainWindow.webContents.openDevTools()//当窗口关闭时发出.mainWindow.on('关闭', function () {//取消引用窗口对象,通常你会存储窗口//如果您的应用程序支持多窗口,则在数组中,这是时间//什么时候应该删除相应的元素.主窗口 = 空})}//这个方法会在 Electron 完成时调用//初始化并准备好创建浏览器窗口.//某些API只有在该事件发生后才能使用.app.on('准备好', createWindow)//当所有窗口都关闭时退出.app.on('window-all-close', function () {//在 OS X 上,应用程序及其菜单栏很常见//在用户使用 Cmd + Q 明确退出之前保持活动状态if (process.platform !== 'darwin') {app.quit()}})app.on('激活', function () {//在 OS X 上,当//停靠图标被单击并且没有其他窗口打开.if (mainWindow === null) {创建窗口()}})//在此文件中,您可以包含应用程序特定主进程的其余部分//代码.您也可以将它们放在单独的文件中并在此处要求它们.//setAsDefaultProtocolClient 仅适用于应用程序的打包版本app.setAsDefaultProtocolClient('myApp')//osx 的协议处理程序app.on('open-url', function (event, url) {event.preventDefault();log("打开 url 事件:" + url)dialog.showErrorBox('open-url', `你来自:${url}`)})//在终端和浏览器都记录功能日志{控制台日志if (mainWindow && mainWindow.webContents) {mainWindow.webContents.executeJavaScript(`console.log("${s}")`)}}

<小时>

实现生活的步骤:-)

# 克隆这个仓库git 克隆 https://github.com/oikonomopo/electron-deep-linking-mac-win.git# 进入仓库cd 电子深度链接-mac-win# 安装依赖npm 安装# 运行应用程序npm 开始# 生成安装程序npm 运行 dist

运行安装程序(electron-deep-linking-mac-win/dist/electron-quick-start-1.0.0.dmg)后,我尝试打开 electron-deep-linking-具有深度链接的操作系统应用,在 Safari 地址栏输入 myapp://param.

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

  2. 如果应用关闭,它会打开,对话框会显示正确的 url,但不会记录到开发控制台!

为什么 dialog 模块 url 显示正确,但没有记录到开发控制台?如何记录?

寻找解决方案只使用 electron-builder(使用electron-packager)!

解决方案

macOS 和 win32 均已解决(更新项目 'electron-deep-linking-GitHub上的mac-win').

<小时>

package.json:

{名称":电子深度链接-macos-win32",版本":0.0.1","description": "带有深度墨迹的最小电子应用程序 (macOS/win32)","main": "main.js",脚本":{开始":电子.","pack": "构建 --dir",dist":构建"},存储库":https://github.com/oikonomopo/electron-deep-linking-osx",作者":oikonomopo",许可证":CC0-1.0",开发依赖":{电子":1.6.6",电子制造商":17.1.2"},建造": {appId":oikonomopo.electron-deeplinking-macos-win32",协议":{"name": "电子深度链接",方案":[myapp"]},苹果电脑": {类别":public.app-category.Reference"},赢": {}}}

<小时>

main.js:

const {app, BrowserWindow} = require('electron')//带有用于处理文件和目录路径的实用程序的模块.常量路径 = 要求('路径')//带有用于 URL 解析和解析的实用程序的模块.常量 url = 要求('url')//保持窗口对象的全局引用,如果不这样做,窗口将//当 JavaScript 对象被垃圾回收时自动关闭.让主窗口//深层链接网址让 deeplinkingUrl//强制单实例应用const shouldQuit = app.makeSingleInstance((argv, workingDirectory) => {//有人试图运行第二个实例,我们应该关注我们的窗口.//win32 的协议处理程序//argv:第二个实例(命令行/深层链接)参数的数组if (process.platform == 'win32') {//只保留命令行/深层链接参数deeplinkingUrl = argv.slice(1)}logEverywhere("app.makeSingleInstance#" + deeplinkingUrl)如果(赢){if (win.isMinimized()) win.restore()win.focus()}})如果(应该退出){app.quit()返回}函数创建窗口(){//创建浏览器窗口.mainWindow = new BrowserWindow({width: 800, height: 600})//并加载应用程序的 index.html.mainWindow.loadURL(url.format({路径名:path.join(__dirname, 'index.html'),协议:'文件:',斜线:真}))//打开开发工具.mainWindow.webContents.openDevTools()//win32 的协议处理程序if (process.platform == 'win32') {//只保留命令行/深层链接参数deeplinkingUrl = process.argv.slice(1)}logEverywhere("createWindow#" + deeplinkingUrl)//当窗口关闭时发出.mainWindow.on('关闭', function () {//取消引用窗口对象,通常你会存储窗口//如果您的应用程序支持多窗口,则在数组中,这是时间//什么时候应该删除相应的元素.主窗口 = 空})}//这个方法会在 Electron 完成时调用//初始化并准备好创建浏览器窗口.//某些API只有在该事件发生后才能使用.app.on('准备好', createWindow)//当所有窗口都关闭时退出.app.on('window-all-close', function () {//在 OS X 上,应用程序及其菜单栏很常见//在用户使用 Cmd + Q 明确退出之前保持活动状态if (process.platform !== 'darwin') {app.quit()}})app.on('激活', function () {//在 OS X 上,当//停靠图标被单击并且没有其他窗口打开.if (mainWindow === null) {创建窗口()}})//定义自定义协议处理程序.//深度链接适用于应用程序的打包版本!app.setAsDefaultProtocolClient('myapp')//osx 的协议处理程序app.on('open-url', function (event, url) {event.preventDefault()deeplinkingUrl = 网址logEverywhere("open-url#" + deeplinkingUrl)})//在开发控制台和正在运行的节点控制台实例上记录功能 logEverywhere(s) {控制台日志if (mainWindow && mainWindow.webContents) {mainWindow.webContents.executeJavaScript(`console.log("${s}")`)}}

main.js 代码说明:

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

Project 'electron-deep-linking-mac-win' is on GitHub.

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"]
    }
  }
}


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

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. If app is opened, it activates and i can see the dialog and the log open-url event: myapp://param!

  2. If app is closed, it opens, dialog is shown with proper url but isn't logged to dev console!

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

Looking for solution using only electron-builder (which uses electron-packager)!

解决方案

Solved for both macOS and win32 ( Updated project 'electron-deep-linking-mac-win' on 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 code description:

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

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