Why target blank is not working in ie 8? [duplicate] - javascript

IE8 will sometimes prevent links from spawning if they have target=_blank set.
This problem appears to be limited to corrupt installs of IE, such as when installing several versions side-by-side.
I edited this question once I found the answer, and hopefully this will save someone else some time. The answer is in the comments of the first answer listed.

This depends upon which stand-alone IE8 that you use. I found this to be a problem while using "Final Builds Site - Internet Explorer Collection" (http://finalbuilds.edskes.net/iecollection.htm) version 1.6.0.3. The developer has now fixed this bug as of Ver. 1.6.0.4, and links with target="_blank" now work as expected.

I know this is already answered, but I just wanted to tell about the jQuery's live binding functionality:
$("a.myclass").live("click",function() {
$(this).attr("target","_blank");
});
This example sets the 'target="_blank"' attribute to any link with the class "myclass", even those created with Javascript.

What about if you use target='blank' ? I know it's not THE same, but you will get the popup/window open in a new instance, and your site could validate for XHTML Strict Mode :)

Yeah, XHTML Strict Mode doesn't accept target="_blank".
If you don't want to keep using window.open everywhere, you can use rel="external" and some extra Javascript like the following, using JQuery:
$(document).ready(function() {
$("a[rel='external']").attr("target","_blank");
});
EDIT: To set all generated links:
$("a[rel='external']").ready(function() {
$("a[rel='external']").attr("target","_blank");
});
Or, without jQuery, you can use the script, found here:
function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href") &&
anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
}
}
window.onload = externalLinks;

This is because target="_blank" is not valid under XHTML Strict Mode. See:
http://www.8164.org/xhtml-strict/
The following should work in all cases.
<script>window.open("http://www.80vul.com/test/ie8-1.htm");</script>
I presume that as of IE8 Beta 1, the default mode is now STRICT instead of TRANSITIONAL.

Related

jQuery 2.0.3 bug - fadeIn(), show() broken in firefox - SecurityError: The operation is insecure

I have a very basic html element that I would like to fadeIn(). I am however using require.js so I believe this could be part of the problem. I am using jQuery 2.0.3 When using fadeIn I get this error:
SecurityError: The operation is insecure.
chrome://firebug/content/console/commandLineExposed.js
Line 5
I have never seen this before, I have reset firefox and my PC.
Html
<message-box>
<message-info></message-info>
<close-box>x</close-box>
</message-box>
JS
$('message-Box').fadeIn();
I only get this error with firefox v27. No other browsers are having this problem, but I haven't tested it in any older versions of FF
I am not seeking help for anything other than the error...
See the error in action? and run this command: SD.message.showMessage('Somehow this breaks everything', 'bad');
-----Edit-------
So sadly you'll need to test this Here I assure you this is SFW, its just the sign in page.
I am confident there must be something in my other JS files that is conflicting, but I, as yet, have not found the problem.
I removed a fiddle that was here as it in no way helped the question, since adding the bounty I want it to be as helpful as possible.
Second Edit
Oddly, when running any show(), hide(), fadeIn() etc an iframe is created at the base of the page, just before the body. I'll need to have a think in my code why this would be happening.
Third Edit
I have no reason or explanation for this, but updating to jQuery 2.1.0 has fixed my issues. If anybody can explain the problem then I'd love to give them the points :)
Stepping through the jQuery code, you eventually hit this internal function below. The security error is thrown when jQuery attempts to write to the iframe document. jQuery 2.1.0 has a different way of determining the default node display value so you can just treat this as a jQuery/browser combo bug. You can minimally recreate the security error by pasting the following into the console:
var iframe = jQuery("<iframe frameborder='0' width='0' height='0'/>").css( "cssText", "display:block !important" ).appendTo(document.documentElement);
iframe[0].contentWindow.document.write("<!doctype html><html><body>");
Internal jQuery function:
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
As per specification custom elements shall have '-' in their tags, so your markup should look like this:
<message-box>
<x-message><div></div></x-message>
<x-close>x</x-close>
</message-box>
After the change and corresponding style updates it works as far as I can tell: http://jsfiddle.net/9Frn8/11/
Looks like this may be due to the absolute paths in your CSS file. I also see (in console) you are trying to do a call to localhost (which fails, of course). There seems to be some issues in your code that is causing Firefox to stop specific processes. Specifically, something that firefox considers cross-domain.
This is most likely a Same-Origin-Policy issue.

can I use console/alert/some-other-means to read out ALL CSS properties at once?

I'm trying to debug a site on iPad. On desktop an element shows, on iPad it's missing.
Question:
Is there a way to output all CSS in one statement similar to
console.log( $('element').attr('class') );
or is the only way to find the faulty property to go through all CSS-rules one by one?
console.log( $('element').css('position') )
console.log( $('element').css('top') )
console.log( $('element').css('left') )
console.log( $('element').css('right') )
console.log( $('element').css('bottom') )
console.log( $('element').css('width') )
console.log( $('element').css('height') )
console.log( $('element').css('display') )
... you get the point...
Thanks for input
You need window.getComputedStyle:
getComputedStyle() gives the final used values of all the CSS
properties of an element.
Supported in every modern browser (including IE9).
A simple example:
var style = window.getComputedStyle($('element').get(0), null);
jsFiddle Demo
It's a lot easier to use some tools to remotely inspect the page on the iPad. iOS 6 will get this built in, but that doesn't helpt much now. If you're on a Mac you can try out iWebInspector along with the iOS SDK. If not, you can check out WeInRe.
Install iOS SDK (free) and iWebInspector
Open iWebInspector
Click "Open iOS Simulator"
Switch to iPad through the menu Hardware -> Device -> iPad
Open Safari and go the page you want to debug
Click "Load from Safari" back in iWebInspector, and chose the page
You should now get the WebKit debugger inside iWebInspector
WeInRe (Webkit Inspector Remote) should work on any platform without the need for iOS SDK. It doesn't work as well as the real debuggers, since it just injects a scripts and only has access to what you get through javascript. But it's a lot easier than printing out all the css programatically ;) Sometimes WeInRe doesn't catch changes to the DOM after you've looked at an element. So wait until the DOM is in the state you want to look at before expanding the parent element. WeInRe is kindly hosted by PhoneGap: debug.phonegap.com, or can be installed on your computer http://phonegap.github.com/weinre/
jquery .css() works better than .getComputedStyle as it accounts for browser difference (and is based on getComputedStyle itself), see http://api.jquery.com/css/
see how to get all the calculated styles of an element with jQuery? and credit the answer there :)
Here's a small plugin that adds $.fn.computedCSS() you can use to get what others have already suggested:
Code:
(function($) {
$.fn.computedCSS = function() {
var elem = $(this)[0];
var styles = window.getComputedStyle(elem);
var computed = {};
for (key in styles) {
if (!key.match(/^\d+$/) && typeof styles[key] !== 'function') {
computed[key] = styles[key];
}
}
return computed;
};
})(jQuery);
Demo:
http://jsfiddle.net/Kd6xR/

Setting an image source via Javascript unreliable in Internet Explorer

I am simply trying to change the SRC attribute of an image via javascript like so:
document.getElementById('fooImage').src = img;
Where img is a variable that has a link to the file.
In all other browsers (Chrome, Firefox, Safari) this works. In IE (7+) this also works too sometimes.
Using IE's built-in developer tools, I can see that the image's SRC tag is set. Is there something else in the locals window that could help me debug why the image doesn't actually show on screen?
I've also tried using jQuery to do this and same outcome:
$("#fooImage").attr("src", img);
An ideas?
In debugging this I would hard code it first...
document.getElementById('fooImage').src = "myimage.png";
I've used the following in my website and it works like this...
var imgCounter = document.getElementById('formtimer');
imgCounter.src = "graphics/odometers/1.png";
Some other things to check:
Make sure your ID= tag is not in the <DIV section but inside the <IMG section... for example <div class="style1"><img src="yourpicture" id="someid">. If `id='someid' is in the div tag then you can't change the picture / the picture won't show up.
are you using window.onload?, body onload? the proper way to use the first is..
window.onload = function () { YourFunctionHere(); };
Try a different test image. I had issues in the past with showing png's, I changed it to a gif or jpg and it worked. I don't understand how that was "way back" but it doesn't seem to be an issue anymore but hey... something to try.
try a full url
using https?
try sticking the image somewhere else in your program and see what happens.
try adding this to your HTML (put your website in place of mine - lookup BASE href on google for more info)
<BASE href="http://perrycs/" />
Make sure the image isn't hidden behind a layer (I know it works in some browsers)
tell us the website so we can check it out and get more info to help you in debugging this, seeing context (surrounding code) helps...
Given that it works in other browsers, searching on this topic it seems that often the problem is how IE caches images (ref. Epascarello's comment). Your code is the same as what I have - it works fine except in IE10.
I too, faced this conundrum. Then discovered that it works in 'Page Inspector', so after some digging discovered that (in Internet Explorer) by going to Tools.Internet Options.Advanced
uncheck the 'Disable script debugging (Internet Explorer)' and the one below it.
I found that with IE9 after changing an image.src with
var strVar="C:Users/x/Desktop/caution.png"
image.src=strVar
and calling an alert(image.src) I would get something like this n the alertbox:
file:///C:Users/x/Desktop/"C:Users/x/Desktop/caution.png"
So I tried
image.src=strVar.replace(/\"/g,"")
to remove qoutemarks
and it worked!
alert(image.src)
file:///C:Users/x/Desktop/caution.png

Remove all content using pure JS

I'm looking for a way to remove the entire content of a web page using pure Javascript -- no libraries.
I tried:
document.documentElement.innerHTML = "whatever";
but that doesn't work: it replaces the inside of the <html/> element. I'm looking at replacing the entire document, including if possible the doctype and <?xml declaration.
I think a browser rightfully assumes a page with content-type text/html will always be a web page - so whilst you may do something like...
document.body.innerHTML = '';
It will still have some HTML hanging around.
You could try...
document.documentElement.innerHTML = '';
...which left me with <html></html>.
Yi Jiang did suggest something clever.
window.location = 'about:blank';
This will take you to a blank page - an internal mechanism provided by most browsers I believe.
I think however the best solution is to use document.open() which will clear the screen.
var i = document.childNodes.length - 1;
while (i >= 0) {
console.log(document.childNodes[i]);
document.removeChild(document.childNodes[i--]);
}
Removes everything (doctype also) on FF 3.6, Chrome 3.195, and Safari 4.0. IE8 breaks since the child wants to remove its parent.
Revisiting a while later, could also be done like this:
while (document.firstChild) {
document.removeChild(document.firstChild);
}
According to Dotoro's article on the document.clear method, they (since it's deprecated) recommend calling document.open instead, which clears the page, since it starts a new stream.
This way, you avoid the nasty about:blank hack.
One can remove both the <html> element (document.documentElement) and the doctype (document.doctype).
document.doctype.remove();
document.documentElement.remove();
Alternatively, a loop can be used to remove all children of the document.
while(document.firstChild) document.firstChild.remove();
document.open() or document.write() work as well.
After the page has already fully loaded:
document.write('');
document.close();
I believe this will do it
document.clear() //deprecated
window.location = "about:blank" //this clears out everything
I believe this will still leave the doctype node hanging around, but:
document.documentElement.remove()
or the equivalent
document.getElementsByTagName("html")[0].remove()
document.documentElement.innerHTML='';
document.open();
The Document.open() method opens a document for writing.
if you dont use open method, you cant modify Document after set innerhtml to empty string
Live demo
If youre using jQuery here's your solution
<div id="mydiv">some text</div>
<br><br>
<button id="bn" style="cursor:pointer">Empty div</button>
<script type="text/javascript">
$(document).on('click', '#bn', function() {
$("#mydiv").empty();
$("#bn").empty().append("Done!");
});
</script>
If youre using javascript here's your solution
<div id="purejar">some text</div>
<br><br>
<button id="bnjar" onclick="run()" style="cursor:pointer">Empty div</button>
<script type="text/javascript">
var run = function() {
var purejar = document.getElementById("purejar");
var bn = document.getElementById("bnjar");
purejar.innerHTML = '';
bn.innerHTML = 'Done!';
}
</script>
Im just curious as to why you'd want to do that. Now theres no way that I know of to replace absolutely everything down to the doctype declaration but if you are wanting to go to those lengths why not redirect the user to a specially crafted page that has the template you need with the doctype you need and then fill out the content there?
EDIT: in response to comment, what you could do is strip all content then create an iframe make it fill the entire page, and then you have total control of the content. Be aware that this is a big hack and will probably be very painful - but it would work :)
REMOVE EVERYTHING BUT --- !DOCTYPE html ---
var l = document.childNodes.length;
while (l > 1) { var i = document.childNodes[1]; document.removeChild(i); l--; }
TESTED ON FIREFOX WEB INSPECTOR - childNodes[1] IS --- !DOCTYPE html ---

Accessing frames via the DOM in IE

OK, every other browser works fine with the method I have coded so far but for some reason Internet Explorer will not work. I have spent hours of time (more time than actually developing the feature!) on compatibility and am close to giving up!
I have a forum and one of its neat features is the WYSIWYG editor. For that, I essentially have an IFrame that acts as the document:
<iframe name="writer" src="/scripts/blank.html" class="writer"></iframe>
This is the current state of the JavaScript (constantly updated):
function initEditor()
{
w = frames['writer']
wc = g('writerCopy')
if(w == null) return
frames['writer'].document.designMode = 'on'
frames['writer'].document.body.innerHTML = styleSheet+wc.value
frames['writer'].focus()
}
It works partially now, but fails on the line:
frames['writer'].document.body.innerHTML = styleSheet+wc.value
in Internet Explorer with "'frames.writer.document.body' is null or not an object".
I'm not even sure IE supports that designMode.
And, .contentDocument is only IE8, IE7 and less uses .contentWindow.document, but iframe windows are part of the frames-collection.
try this, should be crossbrowser:
<iframe name="writer"></iframe>
frames["writer"].document.body.innerHTML = "some html...";
You need to point your iframe to a dummy document for IE. Just create a file blank.html with the following:
<html><body></body></html>
and set <iframe src="blank.html" ... >
Then you can go about referencing frame.document.body.innerHTML = '...' to your hearts content.
BTW that is a terrible title to a question.
Evidently IE8 does not make frame elements available until the entire parent page has loaded. Also note, you can write to the frame before the parent page loads, but this will overwrite the frame and prevent it from being loaded.
The easy solution is to move the InitEditor() call from inside the body to here:
<body onload="InitEditor()">
Perhaps the iframe isn't loaded yet. I can duplicate your "'frames.writer.document.body' is null or not an object" error. I added a setTimeout around it and it then worked for me.
setTimeout(function () {
frames['writer'].document.body.innerHTML = "some text";
}, 200);
Have you activated IE's debugging facilities?
Am I missing something here? shouldn't you use something like:
window.frames[nameOrNumberOfFrame]...
See also in MSDN:
This collection contains only window
objects and does not provide access to
the corresponding frame and iframe
objects. To access these objects, use
the all collection for the document
containing the objects.
In the end I used frames['frameName'].document.write('someText') but only if the other method fails.

Categories

Resources