当前位置: 首页 > 知识库问答 >
问题:

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

谭铭
2023-03-14

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

“electron deep linking mac win”项目位于GitHub上。

编辑了package.json,遵循“electron builder”快速安装指南生成mac安装程序:

{
  "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,添加代码以注册myappurl方案协议,侦听“打开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

运行安装程序(电子-深-链接-mac-win/dist/electron-quick-start-1.0.0.dmg)后,我尝试打开电子-深-链接-os应用程序与深链接,输入myapp://参数在Safari地址栏。

>

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

    若应用程序关闭,它会打开,对话框会显示正确的url,但不会登录到开发人员控制台!

    为什么withdialogmoduleurl显示正确,但未登录到开发人员控制台?如何记录它?

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

  • 共有2个答案

    饶志
    2023-03-14

    您应该在中设置打开url事件,该事件将根据文档完成启动回调。我在打开文件时也有类似的奇怪行为,直到它在将完成启动回调时被设置。

    您注意到,在您链接到的示例中,他们是这样做的。

    虽然它提到将完成启动,它应该提到这在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)
      })
    });
    
    盛浩阔
    2023-03-14

    已解决macOS和win32(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代码说明:

    >

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

    >

    在win32平台上,它与其他参数一起保存在process.argv。要只获取提供的url,深度链接Url=argv.slice(1)。(请参见win32的//协议处理程序)

    app.makeSingleInstance方法中,我们检查我们是哪个平台,并相应地设置深度链接URL!如果我们在win32平台上,url位于回调的Argv变量处,否则macOS上应该已经在'open-url'事件中设置了!(参见//强制单实例应用程序

     类似资料:
    • 我在Android上使用了一个用Ionic构建的应用程序中的deep link。当我点击链接时,应用程序打开了,但仅仅一秒钟后就崩溃了。如何调试此问题? 这是AndroidManifest.xml中的意图代码: 更新 通过使用Android Studio,我有以下日志:

    • 如果应用程序已由Deep link打开,则Deep link不起作用。 但是,如果我不是通过触发深度链接来打开应用程序,比如单击应用程序图标来打开应用程序。之后触发deeplink将一直有效。 详情如下: 所以我在AndroidManifest中设置了这样的活动,即LaunchActivity。 在LaunchActive中,我将打印一个日志,以表明它已经在那里。 我用了 测试深层链接。 应用程序

    • 我想为我的cordova android应用程序启用应用程序索引,如下所述:https://developers.google.com/app-indexing/webmasters/app 不幸的是,我找不到留档如何做一个科尔多瓦的应用程序。有一个插件收听和广播意向,但我不认为这将帮助我在这种情况下:https://github.com/Initsogar/cordova-webintent 我

    • 我有一个与深度链接过程有关的问题。我需要创建一个通用URL,并将其发送到最终用户的电子邮件地址,该地址应满足以下条件。 如果电子邮件在android手机中打开,那么该链接应该打开我的应用程序(带有自定义数据),否则将重定向到Play Store以安装我的应用程序。 如果电子邮件在iOS手机中打开,那么该链接应该打开我的应用程序(带有自定义数据),否则将重定向到AppleiTunesStore以安装

    • 本文向大家介绍php打开本地exe程序,js打开本地exe应用程序,并传递相关参数方法,包括了php打开本地exe程序,js打开本地exe应用程序,并传递相关参数方法的使用技巧和注意事项,需要的朋友参考一下 实例如下: 以上这篇php打开本地exe程序,js打开本地exe应用程序,并传递相关参数方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

    • 我的应用程序使用的是谷歌应用程序邀请框架(firebase之前的版本),电子邮件邀请中的链接工作正常,用户点击链接,应用程序打开并检索到深度链接。然而,当用户通过短信发送时,嵌入链接反而打开play store?用户点击打开应用但没有链接? 就好像短信链接看不到用户设备上的应用程序一样,你有什么想法吗? 有点像我错过了短信打开应用程序的权限? 用于链接检索的清单摘录: 和我的邀请建造者代码: 更新