提交 e796d6cb authored 作者: 蔡芬's avatar 蔡芬

无法关闭窗口

上级 26a76afe
"use strict";
import { app, protocol, BrowserWindow, shell, Menu, ipcMain, globalShortcut } from "electron";
import path from 'path';
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
import { downloadFile, openFile, openFileFolder, getFilePositionFromUrl } from '@/libs/utils/backfunction.js';
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 } },
]);
//热加载
try {
require('electron-reloader')(module);
} catch {}
async function createWindow() {
// 关闭顶部导航菜单栏
Menu.setApplicationMenu(null)
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
center: true, //窗口居中
title: "飞稻平台", //如果由loadURL()加载的HTML文件中含有标签<title>,此属性将被忽略
icon: path.join(__static, '/favicon.ico'), //图标更换,仅支持svg、ico ,在public下
// resizable:false, //窗口大小是否可以改变
// maximizable: false, //窗口是否可以最大化
// frame: false, //无边框窗口 - 去掉顶部导航,关闭按钮,最大最小化按钮
webPreferences: {
// Required for Spectron testing
// enableRemoteModule: !!process.env.IS_TEST,
// 在electron 10.0.0之后,remote模块默认关闭
// 必须手动设置webPreferences中的enableRemoteModule为true之后才能使用
enableRemoteModule: true, // 这里是关键设置
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
// nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
// contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
nodeIntegration: true, //web开启主进程中集成node
// 在独立JavaScript环境中运行Electron API和指定的preload脚本
contextIsolation: false,
preload: path.join(__dirname, 'preload.js')
},
});
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
});
// 注册一个'CommandOrControl+Shift+i' 快捷键监听器
const ret = globalShortcut.register('CommandOrControl+Shift+i', function () {
win.webContents.openDevTools()
});
if (!ret) {
console.log('registration failed')
}
//检查快捷键是否注册成功
// console.log(globalShortcut.isRegistered('CommandOrControl+X'))
// win.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {
// event.preventDefault()
// Object.assign(options, {
// // modal: true,
// // parent: win,
// title: frameName,
// frame: false,
// width: 300,
// height: 400
// })
// // 创建新的窗口
// var a = new BrowserWindow(options)
// a.loadURL(url)
// ipcMain.on('close-app', () => {
// // 通知关闭
// a.close();
// ipcMain.removeAllListeners('close-app')
// });
// // if (!process.env.IS_TEST) a.webContents.openDevTools()
// })
var downloadpath = '';
var folderpath = '';
win.webContents.session.on('will-download', (event, item, webContents) => {
//设置文件存放位置
// console.log(folderpath,item.getFilename(),folderpath+`\\${item.getFilename()}`,'C:/Users/mayn/Downloads/test/'+`${item.getFilename()}`)
item.setSavePath(folderpath+`\\${item.getFilename()}`);
// item.setSavePath('C:/Users/mayn/Downloads/test/'+`${item.getFilename()}`);
item.on('updated', (event, state) => {
console.log(`Received bytes: ${item.getReceivedBytes()}`)
if (state === 'interrupted') {
console.log('Download is interrupted but can be resumed')
} else if (state === 'progressing') {
if (item.isPaused()) {
console.log('Download is paused')
} else {
console.log(`Received bytes: ${item.getReceivedBytes()}`)
}
}
})
item.once('done', (event, state) => {
if (state === 'completed') {
console.log('Download successfully')
} else {
console.log(`Download failed: ${state}`)
}
})
});
ipcMain.on('downLoadFile', (evt,{downLoadUrl,targetUrl}) => {
targetUrl = targetUrl.replace(/\\/g, '/');
targetUrl = targetUrl + '/' +downLoadUrl.substring(downLoadUrl.lastIndexOf('/')+1);
console.log('主进程监听到下载',downLoadUrl,targetUrl);
downloadFile(downLoadUrl, targetUrl,({percentage,received,total,success,filepath, filePosition})=>{
if(!!success) {
console.log('文件下载成功');
// 下载完成打开文件
let openStatus = openFile(filepath); //同浏览器效果 - 打开文件
// let openStatus = openFileFolder(filepath);
// console.log('打开文件位置状态',openStatus,filepath)
return;
}
// console.log(percentage + "% | " + received + " bytes out of " + total + " bytes.");
});
// electron 的下载一直 interrupted -- 失败
// downloadpath = downLoadUrl;
// folderpath = targetUrl;
// evt.sender.send('tips',downloadpath);
// win.webContents.downloadURL(downloadpath);
});
}
ipcMain.on('fromFullPage', e => {
console.log('主进程监听到渲染进程');
});
// 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();
}
});
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 () => {
// 不加载VUEJS_DEVTOOLS
// 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();
});
//所有第三方链接,都通过默认浏览器打开
// app.on('web-contents-created', (e, webContents) => {
// webContents.on('new-window', (event, url) => {
// event.preventDefault();
// shell.openExternal(url);
// });
// });
// 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();
});
}
}
"use strict"; "use strict";
import { app, protocol, BrowserWindow, shell, Menu, ipcMain, globalShortcut } from "electron"; import { app, protocol, BrowserWindow, Menu
import path from 'path'; } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib"; import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer"; import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
import { downloadFile, openFile, openFileFolder, getFilePositionFromUrl } from '@/libs/utils/backfunction.js';
const isDevelopment = process.env.NODE_ENV !== "production"; const isDevelopment = process.env.NODE_ENV !== "production";
// Scheme must be registered before the app is ready // Scheme must be registered before the app is ready
...@@ -17,38 +16,19 @@ try { ...@@ -17,38 +16,19 @@ try {
require('electron-reloader')(module); require('electron-reloader')(module);
} catch {} } catch {}
async function createWindow() { async function createWindow() {
// 关闭顶部导航菜单栏
Menu.setApplicationMenu(null)
// Create the browser window. // Create the browser window.
const win = new BrowserWindow({ const win = new BrowserWindow({
width: 800, width: 800,
height: 600, height: 600,
center: true, //窗口居中
title: "飞稻平台", //如果由loadURL()加载的HTML文件中含有标签<title>,此属性将被忽略
icon: path.join(__static, '/favicon.ico'), //图标更换,仅支持svg、ico ,在public下
// resizable:false, //窗口大小是否可以改变
// maximizable: false, //窗口是否可以最大化
// frame: false, //无边框窗口 - 去掉顶部导航,关闭按钮,最大最小化按钮
webPreferences: { webPreferences: {
// Required for Spectron testing // Required for Spectron testing
// enableRemoteModule: !!process.env.IS_TEST, enableRemoteModule: !!process.env.IS_TEST,
// 在electron 10.0.0之后,remote模块默认关闭
// 必须手动设置webPreferences中的enableRemoteModule为true之后才能使用
enableRemoteModule: true, // 这里是关键设置
// Use pluginOptions.nodeIntegration, leave this alone // Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
// nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION, nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
// contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION, contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
nodeIntegration: true, //web开启主进程中集成node
// 在独立JavaScript环境中运行Electron API和指定的preload脚本
contextIsolation: false,
preload: path.join(__dirname, 'preload.js')
}, },
}); });
...@@ -61,99 +41,7 @@ async function createWindow() { ...@@ -61,99 +41,7 @@ async function createWindow() {
// Load the index.html when not in development // Load the index.html when not in development
win.loadURL("app://./index.html"); win.loadURL("app://./index.html");
} }
win.on('closed', () => {
win = null
});
// 注册一个'CommandOrControl+Shift+i' 快捷键监听器
const ret = globalShortcut.register('CommandOrControl+Shift+i', function () {
win.webContents.openDevTools()
});
if (!ret) {
console.log('registration failed')
}
//检查快捷键是否注册成功
// console.log(globalShortcut.isRegistered('CommandOrControl+X'))
// win.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {
// event.preventDefault()
// Object.assign(options, {
// // modal: true,
// // parent: win,
// title: frameName,
// frame: false,
// width: 300,
// height: 400
// })
// // 创建新的窗口
// var a = new BrowserWindow(options)
// a.loadURL(url)
// ipcMain.on('close-app', () => {
// // 通知关闭
// a.close();
// ipcMain.removeAllListeners('close-app')
// });
// // if (!process.env.IS_TEST) a.webContents.openDevTools()
// })
var downloadpath = '';
var folderpath = '';
win.webContents.session.on('will-download', (event, item, webContents) => {
//设置文件存放位置
// console.log(folderpath,item.getFilename(),folderpath+`\\${item.getFilename()}`,'C:/Users/mayn/Downloads/test/'+`${item.getFilename()}`)
item.setSavePath(folderpath+`\\${item.getFilename()}`);
// item.setSavePath('C:/Users/mayn/Downloads/test/'+`${item.getFilename()}`);
item.on('updated', (event, state) => {
console.log(`Received bytes: ${item.getReceivedBytes()}`)
if (state === 'interrupted') {
console.log('Download is interrupted but can be resumed')
} else if (state === 'progressing') {
if (item.isPaused()) {
console.log('Download is paused')
} else {
console.log(`Received bytes: ${item.getReceivedBytes()}`)
}
}
})
item.once('done', (event, state) => {
if (state === 'completed') {
console.log('Download successfully')
} else {
console.log(`Download failed: ${state}`)
}
})
});
ipcMain.on('downLoadFile', (evt,{downLoadUrl,targetUrl}) => {
targetUrl = targetUrl.replace(/\\/g, '/');
targetUrl = targetUrl + '/' +downLoadUrl.substring(downLoadUrl.lastIndexOf('/')+1);
console.log('主进程监听到下载',downLoadUrl,targetUrl);
downloadFile(downLoadUrl, targetUrl,({percentage,received,total,success,filepath, filePosition})=>{
if(!!success) {
console.log('文件下载成功');
// 下载完成打开文件
let openStatus = openFile(filepath); //同浏览器效果 - 打开文件
// let openStatus = openFileFolder(filepath);
// console.log('打开文件位置状态',openStatus,filepath)
return;
}
// console.log(percentage + "% | " + received + " bytes out of " + total + " bytes.");
});
// electron 的下载一直 interrupted -- 失败
// downloadpath = downLoadUrl;
// folderpath = targetUrl;
// evt.sender.send('tips',downloadpath);
// win.webContents.downloadURL(downloadpath);
});
} }
ipcMain.on('fromFullPage', e => {
console.log('主进程监听到渲染进程');
});
// Quit when all windows are closed. // Quit when all windows are closed.
app.on("window-all-closed", () => { app.on("window-all-closed", () => {
...@@ -186,14 +74,6 @@ app.on("ready", async () => { ...@@ -186,14 +74,6 @@ app.on("ready", async () => {
createWindow(); createWindow();
}); });
//所有第三方链接,都通过默认浏览器打开
// app.on('web-contents-created', (e, webContents) => {
// webContents.on('new-window', (event, url) => {
// event.preventDefault();
// shell.openExternal(url);
// });
// });
// Exit cleanly on request from parent process in development mode. // Exit cleanly on request from parent process in development mode.
if (isDevelopment) { if (isDevelopment) {
if (process.platform === "win32") { if (process.platform === "win32") {
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论