跳到主要內容

原生檔案拖放

概觀

某些處理檔案的應用程式可能希望支援作業系統的原生檔案拖放功能。將檔案拖曳到網頁內容中是很常見的,並且許多網站都支援。Electron 還額外支援將檔案和內容從網頁內容拖曳到作業系統的世界中。

若要在您的應用程式中實作此功能,您需要在回應 ondragstart 事件時呼叫 webContents.startDrag(item) API。

範例

一個範例,示範如何建立一個動態檔案以拖曳出視窗。

Preload.js

preload.js 中,使用 contextBridge 注入一個方法 window.electron.startDrag(...),該方法將傳送 IPC 訊息到主程序。

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electron', {
startDrag: (fileName) => ipcRenderer.send('ondragstart', fileName)
})

Index.html

將可拖曳元素新增到 index.html,並參考您的渲染器腳本

<div style="border:2px solid black;border-radius:3px;padding:5px;display:inline-block" draggable="true" id="drag">Drag me</div>
<script src="renderer.js"></script>

Renderer.js

renderer.js 中,設定渲染器程序以透過呼叫您透過上面的 contextBridge 新增的方法來處理拖曳事件。

document.getElementById('drag').ondragstart = (event) => {
event.preventDefault()
window.electron.startDrag('drag-and-drop.md')
}

Main.js

在主程序(main.js 檔案)中,使用要拖曳的檔案路徑和圖示來擴充接收到的事件

const { app, BrowserWindow, ipcMain } = require('electron/main')
const path = require('node:path')
const fs = require('node:fs')
const https = require('node:https')

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

win.loadFile('index.html')
}

const iconName = path.join(__dirname, 'iconForDragAndDrop.png')
const icon = fs.createWriteStream(iconName)

// Create a new file to copy - you can also copy existing files.
fs.writeFileSync(path.join(__dirname, 'drag-and-drop-1.md'), '# First file to test drag and drop')
fs.writeFileSync(path.join(__dirname, 'drag-and-drop-2.md'), '# Second file to test drag and drop')

https.get('https://img.icons8.com/ios/452/drag-and-drop.png', (response) => {
response.pipe(icon)
})

app.whenReady().then(createWindow)

ipcMain.on('ondragstart', (event, filePath) => {
event.sender.startDrag({
file: path.join(__dirname, filePath),
icon: iconName
})
})

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})

啟動 Electron 應用程式後,嘗試將項目從 BrowserWindow 拖放到您的桌面上。在本指南中,該項目是位於專案根目錄中的 Markdown 檔案

Drag and drop