`base` tag causes iframe to open as new window in Internet Explorer

html, iframe, internet-explorer, javascript

Solution

I just removed the `/msie/.test(navigator.userAgent.toLowerCase()) ||` part, and works fine on IE8. Are you sure that you need this piece of code?

However, whether you don't want remove this piece, you can remove the `base` tag and add it after you create the `iframe`:

load_iframe('main', 250, 300);
//and then:
var hd = document.getElementsByTagName("head")[0];
var bs = document.createElement("base");
bs.target= "_blank";
hd.appendChild(bs);

I tested on chrome, IE8, IE11 and works perfectly!

Problem

I have a problem with the `base` tag which only affects Internet Explorer (versions 8, 9 and 10). The following code is used to open dynamic content in an iframe and it functions correctly in Chrome and Firefox. It also functions correctly in Internet Explorer, but only without the `<base target="_blank"/>` tag. The inclusion of this tag causes the iframe to open as a new window (which makes sense, however this is not what I am trying to do. ``` <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <base target="_blank"/> </head> <body> <div id="main"></div> <script type="text/javascript"> function load_iframe(name, height, width) { var div = document.getElementById(name); var ifrm = document.createElement('iframe'); ifrm.id = 'iframe_' + name; ifrm.frameBorder = 0; ifrm.scrolling = 'no'; ifrm.noresize = 'noresize'; ifrm.marginheight = 0; ifrm.marginwidth = 0; if (height !== 0) { ifrm.height = height; } if (width !== 0) { ifrm.width = width; } div.appendChild(ifrm); content = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head></head><body></body></html>'; if (/msie/.test(navigator.userAgent.toLowerCase()) || window.opera) { ifrm.contentWindow.contents = content; return ifrm.src = 'javascript:window["contents"]'; } else { doc = ifrm.contentDocument; doc.open(); doc.write(content); doc.close(); return ifrm; } } load_iframe('main', 250, 300); </script> </body> </html> ``` How can I fix this issue? Unfortunately, I couldn't get the code to work in a fiddle, perhaps because it relies on `<base/>` being in the `<head>`.

Original source