Prevent iFrame from being busted by dropping a link

1k views Asked by At

I have a page that embeds an iFrame with an external domain. So I can't insert anything into its DOM. The page is run with Node-Webkit (based on Chromium), but since this behavior is the same for any browser, I consider this to be a general JavaScript problem.

I want to prevent users from "dropping links" into my page and into the iFrame.

For my page, I can embed a small JavaScript snippet that listens to the specific events, e.g. "drop" or "dragend":

// prevent dragging & dropping links into this application:
function handleDragEvent(e) {
    e.preventDefault();
    e.stopPropagation();
    return false;
}
var dragEvents = ['dragend',  'drop', 'dragenter', 'dragleave', 'dragover'];
for (var i = 0; i < dragEvents.length; i++) {
    window.removeEventListener(dragEvents[i], handleDragEvent);
    window.addEventListener(dragEvents[i], handleDragEvent);
}

So far, everything works fine: Links dropped into my page won't be navigated to. Links dragged from inside my page into the iFrame won't navigate, but still can be dragged into an external browser window (which could be prevented with "dragstart", but it's okay for me).

But if the user drops a link from an external browser directly into the iframe, it "hijacks" the whole window - not just the iframe. That's what I want to prevent.

I set up a small jsfiddle that demonstrates this odd behavior (tested with Firefox and Chrome).

Question: How do I prevent the browser from changing the top location, if someone drops a link into the iFrame from an external window?

2

There are 2 answers

1
Max On

I cant tell if you are worried about this in normal browsers or in node-webkit?

If you're asking about node-webkit (now called nwjs) then have you tried using nwfaketop on your iframe?

I think the info on this page may be what your after: https://github.com/nwjs/nw.js/wiki/Mini-browser-in-iframe

0
kaape On

There is a related issue for nw.js here: https://github.com/nwjs/nw.js/issues/4914

It seems the only possibility to change the drag & drop behaviour of an iframe is to add an event listener to the loaded iframe (listen for the 'load' event) and override the default behaviour, e.g. for the 'dragover' event:

// identify the iframe element
var frameElem = document.getElementById('main');

frameElem.contentWindow.addEventListener('dragover', function(e){
  e.preventDefault();
  e.stopPropagation();
}, false);