Getting SCRIPT5009: 'id' is undefined in Internet Explore IE 11 - javascript

I have a very simple script(setUser) which is called on click of a button.This script is working fine in chrome but in IE 11 i am getting a console error.
Another weird thing is i am getting that error only when dev tool is open.It works fine if devtool is not open.
Error is :-
SCRIPT5009: 'id' is undefined
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function setUser(eventType){
console.log(eventType);
}
</script>
</head>
<body>
<button id="vish" onclick="setUser(id)" style="height:40px;width:200px">Click Me</button>
</body>
</html>
Simple Workaround for this is to declare a
var id; just below the script.But i need the proper documented reason why this doesnot work in ie11 but same works in chrome.And is a better solution than what i tried
Workaround :- by adding var id at the top
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
var id;
function setUser(eventType){
console.log(eventType);
}
</script>
</head>
<body>
<button id="vish" onclick="setUser(id)" style="height:40px;width:200px">Click Me</button>
</body>
</html>
expected :-
when dev tool is open in ie11 and when we click the button we should get the console log as "vish"
actual result :-
SCRIPT5009: 'id' is undefined js error

id is simply undefined, as the error message says. If you declare it, the error is gone, but it won't behave like you expected. If you declare it, it exists with value undefined. You probably wanted
onclick="setUser(this.id)"
this.id means the button context, while simply id tries to find it in global context. In case of your error, id is not declared, whereas
var id; // or var id=undefined;
declares it, and leaves it undefined, so the browser at least knows it is a variable. By saying id is undefined Explorer means it is not declared.
I believe the reason is that the browser searches for variables and named elements (referenced by name or id attribute; this is not standard, but browsers do it), which actually doesn't exist in global context and are looked up by reference and Explorer obviously can't handle this situation. If it is declared as var, javascript knows it is not a named element reference.
Example below shows the non-standard behaviour: it should end with error test is not defined (it really is not), but browsers say hello.
<input id="test" value="hello">
<script>
alert(test.value);
</script>

The cause of it not working in IE11 is because you do not specify a doctype for the HTML document in the block of code that threw the error.
If I add <!DOCTYPE html> to the start of the HTML, as in the workaround you show; it works in IE11 as well for me, without adding the var id;
The exact reason is unknown to me, but without the doctype, IE will run the page in quirks mode. And that seems to mess up the determination of the function scope when the browser tries to parse onclick="setUser(id)" into valid JS code.
This would not happen if the doctype is correct and the page can hence be run in the correct mode.
This would also no happen if the browsers HTML engine did not have to parse the HTML string setUser(id) into valid JS code before it can be used. Hence it's not a common issue anymore since the standard these days is to not use inline event handler attributes on HTML tags.
So prefer explicit event binding with javascript when possible to not run into issues like this, where a totally unrelated part, the doctype, messes up your code.

Using onclick="setUser(this.id)" should work.
However, a cleaner workaround would be to do all the onclick handling in JavaScript:
onload = function() {
var buttons = document.getElementsByTagName("button");
for(var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function() {
console.log(this.id);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="vish" style="height:40px;width:200px">Click Me</button>
<button id="vish2" style="height:40px;width:200px">Click Me 2</button>
</body>
</html>

Related

contentDocument property is undefined for xml document

I am trying to use Mozilla's documentation about removing xml dataislands. The code from the same is failing for weird reasons. Here is the link. https://developer.mozilla.org/en/docs/Using_XML_Data_Islands_in_Mozilla
Exact code
`<!DOCTYPE html>
<html>
<head>
<title>XML Data Block Demo</title>
<script>
function runDemo() {
var doc = document.getElementById("purchase-order").contentDocument;
var lineItems = doc.getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "lineItem");
var firstPrice = lineItems[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "price")[0].textContent;
document.getElementById("output-box").textContent = "The purchase order contains " + lineItems.length + " line items. The price of the first line item is " + firstPrice + ".";
}
</script>
</head>
<body onload="runDemo()";>
<object id="purchase-order" data="purchase_order.xml" type="text/xml" style="display: none;"></object>
<div id="output-box">Demo did not run</div>
</body>
</html>
In this code, var doc = document.getElementById("purchase-order").contentDocument; line is causing the error object does not support contentDocument property in both Chrome and IE.
What am I possibly missing here?
Edit:
I found the issue with IE. IE does not support this property in compatibility mode. Removed the compatibility mode and it works fine now.
But same thing still fails in Chrome. I don't think there is a compatibility mode enabled in chrome. So no idea why chrome is failing.
Edit:
This was supposed to be in continuation of the methods I was trying to remove XML dataisland. I think, updating the old question is a better idea.

what does "JavaScript sanitization doesn't save you from innerHTML" mean?

I'm learning xss prevention through this ppt:http://stash.github.io/empirejs-2014/#/2/23, and I have a question on this page.
It says "JavaScript sanitization doesn't save you from innerHTML", and I tried a simple test like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="test"></div>
<script>
var userName = "Jeremy\x3Cscript\x3Ealert('boom')\x3C/script\x3E";
document.getElementById('test').innerHTML = "<span>"+userName+"</span>";
</script>
</body>
</html>
when I opened this html on my browser(chrome), I only saw the name "Jeremy",by using F12, I saw
<div id="test"><span>Jeremy<script>alert('boom')</script></span></div>
Although the script had been added to html, the alert box didn't come out.
"JavaScript sanitization doesn't save you from innerHTML" I think this means that the word "boom" should be alerted. Am I right?
According to MDN, innerHTML prevents <script> elements from executing directly1, which means your test should not alert anything. However, it does not prevent event handlers from firing later on, which makes the following possible:
var name = "\x3Cimg src=x onerror=alert(1)\x3E";
document.getElementById('test').innerHTML = name; // shows the alert
<div id="test"></div>
(script adapted from the example in the article, with escape sequences although I'm not sure those are relevant outside of <script> elements)
Since <script> elements never execute when inserted via innerHTML, it's not clear to me what that slide is trying to convey with that example.
1 This is actually specified in HTML5. MDN links to a 2008 draft; in the current W3C Recommendation, it's located near the end of section 4.11.1, just before section 4.11.1.1 begins:
Note: When inserted using the document.write() method, script elements execute (typically synchronously), but when inserted using innerHTML and outerHTML attributes, they do not execute at all.

IE11-facing issue while calling focus() on window object

Trying to run a following simple code on IE11 browser:
<!DOCTYPE html>
<html>
<head>
<title>Popup Example</title>
<script>
function ButtonClick2() {
var thewin = window.open("http://www.google.com",'thewin','width=400, height=420,status=no');
window.thewin.focus();
}
</script>
</head>
<body>
<button onclick="ButtonClick2()">Click Me!</button>
</body>
</html>
ISSUE:On IE11 it gives the error statement "Unable to get property 'focus' of undefined or null reference"
This answer's late, but I thought that I'd post it just in case somebody came across this question in the future.
According to the answer here: https://stackoverflow.com/a/7025648/1600090,
and my own experience, one possible cause could be that you're trying to open a window in a different internet zone for which Protected Mode is enabled. By default, IE11 enables Protected Mode for the Internet and Restricted zones but disables it for Local Intranet and Trusted Sites. So, for example, if your page (and/or site) are running in your Local Intranet zone and you're trying to open a new window in the Internet zone, window.open is going to return a null reference. If the page/site which is launching the new window is in the Internet zone, in my experience, window.open will return a reference. So, #ssut's example in jsfiddle is going to work because jsfiddle.com and google.com are probably both in the same zone (I'm assuming the Internet zone).
Please check the variable scope. This issue is not browser's problem.
In your code, var thewin = window.open(.. in the ButtonClick2 function, but window.thewin.focus(); is point to window object's thewin variable.
Change the code to thewin.focus(); then it works perfectly.
New code:
PE html>
<html>
<head>
<title>Popup Example</title>
<script>
function ButtonClick2() {
var thewin = window.open("http://www.google.com",'thewin','width=400, height=420,status=no');
thewin.focus();
}
</script>
</head>
<body>
<button onclick="ButtonClick2()">Click Me!</button>
</body>
</html>

Image onload, another error in IE - fairly sure it's not a caching error

This code is the core of a much larger script that works great in almost all browsers. Yet it didn't work in IE. So I've stripped it down and found that the image.onload isn't firing in IE.
I've done some research, and I've guarded against it being an image caching problem. For one, the error occurs first time round before anything is cached, and, more importantly, the onload event is attached before the src.
I'm also reasonably sure I'm attaching the onload event in an IE compatible manner, so what gives, why don't I get an alert?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function generate(){
var imageGen = document.createElement("img");
imageGen.setAttribute('onload',"primer()");
imageGen.setAttribute('src', "http://www.google.co.uk/images/srpr/logo3w.png");
document.getElementById('image').appendChild(imageGen);
}
function primer() {
alert("here now");
}
</script>
</head>
<body onload="generate()">
<div id="image">
</div>
</body>
</html>
I'm hosting a version here
I only have access to IE8 unfortunately, so I don't know if it persists across other versions, even so it needs to be fixed.
First of all, events are not attributes and must not be set using setAttribute. It might, or might not work.
Second, try creating image object instead of image element:
var imageGen = new Image();
imageGen.src = "http://www.google.co.uk/images/srpr/logo3w.png";
imageGen.onload = primer;
document.getElementById('image').appendChild(imageGen);
Live test case - worked fine for me on IE9 and IE9 compatibility mode which should be like IE8.
Can you try imageGen.onload = primer instead of imageGen.setAttribute('onload',"primer()"); ?

document.write with CoffeeScript

I know I am probably doing this wrong because if trying this through try coffeescript feature it works but surprisingly it doesn't emit any result on my example:
<!--http://f.cl.ly/items/1u3Q3W101U2T18162v0V/test.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
</head>
<body>
<script type="text/coffeescript" >
document.write "<h2>TEST</h2>"
</script>
</body>
</html>
The document.write method doesn't seems to output anything to the body, in this case console.log works fine but not document.write
Even after trying to run the script with a onload handler like I use in javascript
var loaded = function(){
alert("hello");
}
document.addEventListener('DOMContentLoaded', loaded);
but then in coffeescript as
loaded = ->
alert "hello"
document.addEventListener "DOMContentLoaded", loaded
it seems neither the event method is being fired as opposed to javascript version
Anyone could help me find out what is happening?
Thanks
UPDATE
if running the console after the page is loaded I can get the following to work without problem:
CoffeeScript.eval('document.write "<h1>testing</h1>"')
but still wondering why the page itself is not showing automatically
Works on Firefox and Chrome but not in Safari
It seems the page is not showing if using Safari 5.0.3
I don't know anything about CoffeeScript, but don't use document.write. It is evil: http://javascript.crockford.com/script.html
Use createElement and appendChild/insertBefore instead:
var p = document.createElement("p");
p.innerHTML = "Lolz";
document.body.appendChild(p);
myDiv = document.getElementById("aDiv");
document.body.insertBefore(p, myDiv);
document.write has problems in Safari as well.
This is a humdinger, but after investigating, I've got your answer:
The way coffee-script.js works is that it looks for, and runs, scripts with type="text/coffeescript" after the document has loaded. In the case of Safari, that means that
<script type="text/coffeescript">
document.write "<h2>TEST</h2>"
</script>
is equivalent to
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function() {
document.write("<h2>TEST</h2>");
}, false);
</script>
which silently fails. Note that making the insertion with the document.createElement method described by Erlend, or with a library like jQuery, will work fine.
Since this works in Chrome, I'd go ahead and call it a Safari bug. But the real moral of the story is: Don't use document.write.

Categories