user187676
user187676

Reputation:

Prevent IFrame Navigation

I use an iframe to display HTML email contents by writing a HTML string to it's content document via JS. I don't want the user to navigate inside that iframe if he clicks a link in the displayed email. Now I have these options:

  1. Open links in a new browser window or tab (preferred)
  2. Prevent all navigation (suboptimal, only if no other option left)
  3. Better option I don't know about?

How could I accomplish any of those 2 options?

I know that HTML5 introduced a sandbox property, but unfortunately that only works in Chrome and Safari, so that's not an option.

Upvotes: 3

Views: 10860

Answers (4)

IliasT
IliasT

Reputation: 4301

For the page the iframe is hosted in, define a CSP that restricts the child-src to a specific source, such as a domain. FYI this doesn't work for Internet Explorer. Here's a related answer.

Upvotes: 3

d2vid
d2vid

Reputation: 2302

If the iframe is from a different origin, this method will prevent navigation by resetting the iframe source if it changes:

  var $iframe = $('iframe');
  var iframeUrl = 'http://example.com/foo';
  var iframeLoaded = false;
  $iframe.on('load', function () {
    if (!iframeLoaded) {  # Allow initial load of iframe.
      iframeLoaded = true;
      return;
    }

    # Reset iframe location back to original source to prevent navigation.
    iframeLoaded = false;
    $iframe[0].src = iframeUrl;
  });

Unfortunately, there's no way to detect the start of the iframe load, so it'll briefly flash the new content before navigating back. Also, be aware that this will break the browser back button.

Upvotes: 4

RobG
RobG

Reputation: 147403

You should be able to replace all links with their displayed text, something like:

var links = document.links;
var i = links.length;
var link, text, node;

while (i--) {
  link = links[i];
  text = link.textContent || link.innerText || '';
  node = document.createTextNode(text);
  link.parentNode.replaceChild(node, link);
}

Note that the links collection is live, hence the reverse loop.

Upvotes: 1

webnoob
webnoob

Reputation: 15934

You could loop through all the links in the iframe and add target="_blank" to them.

(Excuse me but I only know how to do this in JQuery so sorry for linking the example in this without it being tagged in the question):

$("#iframeID").contents().find("a").each(function() {
    $(this).attr("target", "_blank");
});

Example: http://jsfiddle.net/yP7Nd/ - (ignore the bit of JS above my JQuery code, I had to do this to get some IFrame content to load properly).

Upvotes: 1

Related Questions