Nick Ang profile picture

Nick Ang

Make iframe hyperlinks redirect correctly in main document

At work recently we had to figure a way to redirect a user to another webpage when she clicks on a URL. This is obviously a trivial task for 99 percent of cases - just use <a href="">Click</a>. But within an <iframe>, URL redirects can act strangely.

Let’s say you’re building a HTML/CSS/JS recommendation widget that is supposed to be embedded on people’s e-commerce websites. When a user clicks on an image in the widget, you want to redirect her to the product detail page. But because your widget is actually embedded within an iframe (for ease of installation - UX!), when the user clicks on an image, she gets redirected to the product page within the iframe, while the main window remains on the same page. That is unintended behaviour and it needs to be fixed.

Thankfully, the fix in this situation is very, very simple. Apparently there is a HTML element called <base> that handles this.

<base target="_parent">

By adding this line of code in the <head> of your iframe, all URL redirects will happen on the parent document instead of in the iframe document. Something like this:

<!doctype html>
  <link href=",700" rel="stylesheet">

  <!-- Force iframe URL clicks to open in main document -->
  <base target="_parent">

<!-- etc -->

I wish all web-related problems had beautiful, pre-emptive solutions like <base>!

Nick Ang profile picture
Senior software engineer, dad, writer-thinker type. Big on learning something everyday and trying to have fun before the lights go out.
contact  |  subscribe & access all latest posts