Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Electron app from redirecting when drag+dropping items in window

I don't want a drag+drop feature in my app since there is no need for it. So I want to completely remove the drag+drop feature of the window. So far when dragging images the Electron window opens the image path. When dragging links the Electron window redirects to the link.

I have tried calling this:

  document.addEventListener('dragstart',function(event){
    event.preventDefault();
    return false;
  },true);

  document.addEventListener('drop',function(event){
    event.preventDefault();
    return false;
  },true);

event.preventDefault() on the drop event should have worked but it didn't

Also tried this:

  BrowserWindow.on('will-navigate',function(event){
    event.preventDefault();
    return false;
  });

  BrowserWindow.webContents.on('will-navigate',function(event){
    event.preventDefault();
    return false;
  });

Also failed. Any ideas how to fix this?

removeEventListener() failed as well

  var listener = function (event) {
    console.log('foo');
  };
  document.removeEventListener('drop',listener,false);
like image 455
Jo E. Avatar asked Jul 28 '15 08:07

Jo E.


2 Answers

A concise version using ES6 syntax (working for me under Electron 1.4.1)

document.addEventListener('dragover', event => event.preventDefault())
document.addEventListener('drop', event => event.preventDefault())
like image 198
Erik Berkun-Drevnig Avatar answered Sep 22 '22 21:09

Erik Berkun-Drevnig


Found a fix for Windows Electron v2.3.1 Windows Electron v0.30.0 the code should have listeners for both dragover AND drop.

  document.addEventListener('dragover',function(event){
    event.preventDefault();
    return false;
  },false);

  document.addEventListener('drop',function(event){
    event.preventDefault();
    return false;
  },false);

Electron will still redirect to the dropped file if you only listen to dragover or drop.

Cheers!

like image 22
Jo E. Avatar answered Sep 20 '22 21:09

Jo E.