zoukankan      html  css  js  c++  java
  • electron 设置伪协议和文件绑定

    基于 electron-builder

    package.json

    // fileAssociations 为文件关联
    // mac 环境需要在 extendInfo 中配置 CFBundleURLSchemes
    "build": {
        "fileAssociations": {
            "ext": [
                "txt"
            ],
            "role": "Editor"
        },
        "mac": {
          "extendInfo": {
            "CFBundleURLSchemes": [
              "protocol"
            ]
          }
        }
    }
    

    main.js

    let openFromProtocolUrl = ''
    const openUrl = (url) => {
      mainWindow.isMinimized() && mainWindow.restore()
      // 正则中的 protocol 为自己定义的伪协议
      if (url.match(/^protocol:///)) {
        mainWindow.webContents.send('open-url', decodeURIComponent(url))
      } else {
        mainWindow.webContents.send('open-file', url)
      }
      mainWindow.focus()
    }
    if (isWin) {
      const argv = process.argv.slice()
      openFromProtocolUrl = argv.pop() // 启动参数的数组的最后一项是唤醒链接
    }
    
    // 省略代码
    function createWindow() {
      mainWindow = new BrowserWindow({...})
      
      // 从协议打开应用时,mainWindow 还没有创建完成
      setTimeout(() => {
        if (openFromProtocolUrl) {
          openUrl(openFromProtocolUrl)
          openFromProtocolUrl = ''
        }
      }, 1500)
    }
    
    const openUrlListener = function (event, url) {
      if (mainWindow) {
        openUrl(url)
      } else {
        openFromProtocolUrl = url // 如果 mainWindow 还没创建,就先缓存
      }
    }
    app.on('open-url', openUrlListener)
    app.on('open-file', openUrlListener)
    app.setAsDefaultProtocolClient('protocol') // 设置伪协议
    

    渲染进程

    const fileAssociationsReg = /.txt$/g
    const fileOpened = async (path) => {
        const match = path.match(fileAssociationsReg)
        if (!match) return console.log(`%c错误,该文件不为文本:${path}`, 'color:red')
        // 省略
    }
    ipcRenderer.on('open-file', fileOpened)
    
    const urlListener = (event, url) => {
      const payload = url.replace(/protocol:///, '').split('/')
      // 省略
    }
    ipcRenderer.on('open-url', listener)
    
    
  • 相关阅读:
    C语言不定参数
    C和C++中的不定参数
    C/C++ 中头文件相互包含引发的问题
    Makefile经典教程(掌握这些足够)
    C语言中volatile关键字的作用
    C++中字符数组与string的相互转换
    C++中 使用数组作为map容器VAlue值的解决方法
    sql 内连接、外连接、自然连接等各种连接
    网站小图标
    Eclipse:快捷
  • 原文地址:https://www.cnblogs.com/NKnife/p/13475557.html
Copyright © 2011-2022 走看看