Skip to content

Instantly share code, notes, and snippets.

@timpulver
Created September 15, 2016 13:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timpulver/452670e4a0ec9619a06347ff61c3f60c to your computer and use it in GitHub Desktop.
Save timpulver/452670e4a0ec9619a06347ff61c3f60c to your computer and use it in GitHub Desktop.

Electron Drag’n’Drop

Allows files(s) to be dragged inside the electron app as well as files to be dropped out (when dropped on the desktop e.g. the file will be copied to the destination.

Installation

Clone the Quick Start repository:
git clone https://github.com/electron/electron-quick-start

Go into the repository:
cd electron-quick-start

Install additional dependencies:
npm install jquery --save

Install the dependencies and run:
npm install

run

Run npm start

Note: The example also needs an icon to be places inside your app directory: elektron-drag-out-test/img/icon/folder.png, change the path in main.js / renderer.js accordingly. You can grab one from here: flaticon.com

// ... ^^^
// ... original main.js content
// 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.
const {ipcMain} = require('electron')
ipcMain.on('ondragstart', (event, filePath) => {
event.sender.startDrag({
file: filePath,
icon: 'img/icon/folder.png'
})
})
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
var ipcRenderer = require('electron').ipcRenderer
// wait for jQuery to load
function initWhenReady(method) {
if (window.jQuery) {
$(document).ready(init);
} else {
setTimeout(function() { initWhenReady(method) }, 50);
}
}
// check for jQuery and continue when loaded
initWhenReady();
/*
* Initiates the drag events from outside to electron app
*/
function initDragIn(){
window.ondragover = function(e) {
$('body').addClass('file-hover');
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
return false;
};
window.ondrop = function(e) {
e.preventDefault();
$('body').removeClass('file-hover');
for (var i = 0; i < e.dataTransfer.files.length; ++i) {
console.log(e.dataTransfer.files[i].path);
}
return false;
};
window.ondragleave = function () {
$('body').removeClass('file-hover');
return false;
};
}
/*
* Init Drag out (elelctron —> os)
*/
function initDragOut(){
document.getElementById('drag').ondragstart = (event) => {
event.preventDefault()
ipcRenderer.send('ondragstart', '/Users/tim/dev/test/elektron-drag-out-test/img/icon/folder.png')
}
}
/*
* Initiates drag'n'drop
*/
function init(){
initDragIn();
initDragOut();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment