vue + electron实现浏览器ctrl f踩过的坑

文章介绍了如何将Vue项目与Electron集成,使用electron-builder工具打包成exe应用,并在exe中实现浏览器的Ctrl+F功能。同时,提到在preload.js中处理Node环境兼容性和资源管理,以及在Vue组件中监听Electron事件的过程。
摘要由CSDN通过智能技术生成
项目前提:公司用Vue开发了个项目,部署到现场后要求打包成exe应用。
**版本: Node版本 16.13.2    Electron版本 13.6.9**

1、在项目中集成Electron

  1. Vue项目添加Electron-builder打包工具, 添加成功后src文件夹下生成background.js文件
vue add electron-builder
  1. vue.config.js增加配置(打包后不加密)
pluginOptions: {
	electronBuilder: {
		builderOptions: {
			nsis: {
		         allowToChangeInstallationDirectory: true,
		         oneClick: false
			},
			electronDownload: {
				mirror: "https://npm.taobao.org/mirrors/electron/"
			},
			win: {
         		target: "nsis",
				icon: './build/logo.ico', // exe图标 ico要求256*256
			},
			productName: "ILTestClient", // 应用名称
       		asar: false //打包时不进行加密
		}
	}
}

可以在此目录\win-unpacked\resources\app查看打包后的文件和dist相同;

  • 添加完electron-builder后 package.json文件会自动添加相关命令,如下图
    在这里插入图片描述
    在控制台执行npm run electron:build命令,打包exe(双击win-unpacked下的xxx.exe访问程序)。

要在exe程序中增加浏览器的ctrl f 功能

  • 第一步
    在background.js中注册ctrl f 事件,并在各个窗口中监听,直接上代码:
    (遇到的问题:一开始百度的时候搜到的都是设置nodeIntegration为true后在Vue组件引入Electron就可以在Vue页面中监听到electron的事件,但是项目就不能在浏览器访问可能是因为浏览器没有node的运行环境,后面又查了一下可以通过preload.js进行预加载这样浏览器就可以正常访问了)
'use strict'

import { app, protocol, BrowserWindow, Menu, globalShortcut } from 'electron'
const path = require('path')
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
let win;
const isDevelopment = process.env.NODE_ENV !== 'production'
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // 设置菜单为null
  Menu.setApplicationMenu(null)
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    show: false,
    webPreferences: {
      // 预加载node
      preload: path.join(__dirname, '/preload.js'),
      // 开启渲染进程的remote模块
      enableRemoteModule: !!process.env.IS_TEST,
      // enableRemoteModule: true,

      // 开启渲染进程使用node
      // nodeIntegration: false,
      contextIsolation: false
    }
  })
  win.on('ready-to-show', () => {
    win.show()
  })
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
  win.on('closed', () => {
    win = null
  })

  win.on('focus', () => {
    globalShortcut.register('CommandOrControl+F', function () {
      if (win && win.webContents) {
        win.webContents.send('on-find', '')
      }
    })
    // 注册 'ESC' 键的快捷键
    globalShortcut.register('Escape', function () {
      if (win && win.webContents) {
        win.webContents.send('on-esc', '')
      }
    })
  })
  win.on('blur', () => {
    globalShortcut.unregister('CommandOrControl+F')
    globalShortcut.unregister('Escape')
  })
  // win.webContents.openDevTools()
  // 在开发环境和生产环境均可通过快捷键打开devTools
  globalShortcut.register("CommandOrControl+Shift+i", function () {
    win.webContents.openDevTools()
  })
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS 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()
  }
  globalShortcut.unregister('CommandOrControl+F')
  globalShortcut.unregister('Escape')
})

app.on('activate', () => {
  // On macOS 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 (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// 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', async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

preload.js文件内容
在这里插入图片描述
引入preload.js 我把它放在了src下
pluginOptions: {
electronBuilder: {
preload: ‘src/preload.js’,
builderOptions: {
nsis: {
allowToChangeInstallationDirectory: true,
oneClick: false,
},
extraResources: [
{
from: “disable-gpu”,
to: “.”,
filter: ["**/"],
},
],
electronDownload: {
mirror: “https://npm.taobao.org/mirrors/electron/”,
},
win: {
target: “nsis”,
icon: “./build/logo.ico”, // exe图标 ico要求256
256
},
productName: “TestClient”,
asar: false, //打包时不进行加密
},
},
},

  • 第二步 在Vue页面中去监听ctrl 事件什么时候触发(监听on-find事件)
mounted: {
	if (window.ipcRenderer) {
	  // 监听搜索事件
      window.ipcRenderer.on('on-find', (e, args) => {
        this.searchBox = true;
        this.$nextTick(() => {
          this.$refs.findIpt.focus();
        })
        this.searchValue()
      })
      // 监听退出事件
      window.ipcRenderer.on('on-esc', (e, args) => {
        this.searchBox = false
      })
    }
}
  • 打包electron生成exe文件目录如下
npm run electron:build

在这里插入图片描述

  • 12
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue Electron 是一种用于构建跨平台桌面应用程序的开源框架,结合了 Vue.jsElectron.js 技术。在 Vue Electron实现自动更新需要借助 Electron 的 autoUpdater 模块和一些其他辅助工具。 首先,需要在主进程(`main.js`)中配置自动更新。可以使用 Electron 的 autoUpdater 模块来检查新版本,并自动下载和安装更新。具体步骤如下: 1. 导入 autoUpdater 模块:在 `main.js` 文件中添加 `const { autoUpdater } = require('electron-updater')`。 2. 配置更新服务器地址:通过 `autoUpdater.setFeedURL()` 方法设置更新服务器的地址,例如 `autoUpdater.setFeedURL('https://your-update-server-url')`。 3. 监听更新事件:使用 `autoUpdater.on()` 方法监听自动更新过程中的各个事件。例如可以监听 `checking-for-update`、`update-available`、`update-not-available`、`download-progress` 和 `update-downloaded`。 4. 触发检查更新:通过 `autoUpdater.checkForUpdates()` 方法触发检查更新的过程,在应用启动时或者可以通过某个按钮点击事件来手动检查更新。 接下来,需要在渲染进程(Vue 组件)中显示更新提示和进行更新操作。具体步骤如下: 1. 在渲染进程的代码中,可以监听 `message` 事件来接收主进程发送的消息,从而在用户界面上显示更新提示。 2. 监听到更新提示后,可以弹出一个对话框,询问用户是否进行更新。如果用户选择更新,可以通过 `ipcRenderer.send()` 方法向主进程发送消息,触发下载和安装更新的过程。 3. 主进程监听到渲染进程发送的更新请求后,可以通过 `autoUpdater.downloadUpdate()` 方法来下载更新文件。 4. 下载完成后,通过 `autoUpdater.quitAndInstall()` 方法来安装更新并重启应用。 以上就是使用 Vue Electron 实现自动更新的基本步骤。需要注意的是,还需要在应用的打包配置中加入相应的逻辑,以使自动更新在不同平台下运行正常。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值