JavaScript Failure - javascript

I try to learn how to write Javascript but I have found a problem either so basic I would never think about it or so complicated that I lack the knowladge to find it.
I am Using NetbeansIDE 8.0 .
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<head>
<title>Objekt Navigator</title>
</head>
<body>
Something<br/>
<script language="javascript" type="text/javascript">
document.write("Text");
alert("Bla bla");
</script>
Else<br/>
</body>
</html>
If the compiled page is opened it will only display "Something" and "Else" but nothing of the script.
If I remove "document.write("Text");" it will show the alert but there is no wrong wording in "document.write".
I really need one (or more) pointers to understand this.

Pointer 1:
Don't use document.write. Really. It has been archaic and obsolete for at least 15 years, if not 20. Use regular DOM methods.
Whatever tutorial you found that in, choose something else.
Pointer 2: Don't use XHTML. Use the HTML5 Doctype. The XHTML one does some very weird things with JavaScript -- IF the file is being served as XHTML.
Lastly: your code works just fine for me. If this is not the exact code that you are using in your tests, look at your console.log to see if you have an error somewhere.

Related

without type='text/javascript' is okay for ie9? [duplicate]

<script type="text/javascript">
/* ... */
</script>
vs.
<script language="Javascript">
/* ... */
</script>
Which should be used and why?
Or, the third alternative: omitting either of these, such as the example code in jQuery's API reference:
<script src="http://code.jquery.com/jquery-latest.js"></script>
The language attribute has been deprecated for a long time, and should not be used.
When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.
For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>
You will be informed of the following error:
Line 4, Column 41: required attribute "type" not specified
So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.
HTML4/XHTML1 requires
<script type="...">...</script>
HTML5 faces the fact that there is only one scripting language on the web, and allows
<script>...</script>
The latter works in any browser that supports scripting (NN2+).
The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.
The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

Can't run JavaScript in CDATA

I am trying to run following HTML in every browser: Opera, FF, IE, Chrome
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8">
</head>
<body>
<script>
<![CDATA[
alert('Hey!');
]]>
</script>
</body>
</html>
None of them display the alert. Chrome logs an error in console: Uncaught SyntaxError: Unexpected token <. It seems to be complaining about the fist < in CDATA declaration. Firefox also logs "syntax error"
The w3schools point out that this is the way to use CDATA http://www.w3schools.com/xml/xml_cdata.asp. Other answers on this site suggest it. What am I doing wrong? I tried playing with namespaces and doctypes, but that did not change anything.
Edit: I added XHTML name space and doctype, that I originally removed and the problem still persists.
The difference is between HTML and XHTML. W3Schools is correct that it’s a valid CDATA construct within XHTML, but as your question indicates that your code is HTML and there is no such thing as CDATA inside a <script> in HTML, your example fails as soon as the interpreter sees the "<". You can tell the browser that it’s looking at XHTML, but it's probably safer to handle HTML, too. To do that, you need to hide the CDATA inside JavaScript comments. (You might also consider identifying which language is inside your <script> block.)
<html>
<head>
</head>
<body>
<script>
//<![CDATA[
alert('Hey!');
//]]>
</script>
</body>
</html>
This is, in fact, the method recommended by the World Wide Web Consortium (W3C) in XHTML Media Types, A.4. Embedded Style Sheets and Scripts.
The related question When is a CDATA section necessary within a script tag? explains that a CDATA section is recommended when embedding scripts in XHTML documents. However, just setting a XHTML doctype to the test document isn't enough. The CDATA is still being treated as a syntax error.
According to this blog post, that is because the content type needs to match the doctype definition. Proper XHTML needs to have the following Content-type header set:
Content-type: application/xhtml+xml
if that is not specified and text/html sent instead, browsers will revert to HTML. And indeed, if I add that header to my test case, browsers start properly parsing the JavaScript inside the CDATA even when the CDATA it's not commented out.
This works for me (setting the header using PHP):
<?php header("Content-type: application/xhtml+xml");
echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script><![CDATA[alert('Hey!');]]></script>
</head>
<body>
</body>
</html>​
You may see it as XML (XHTML) but that's not how the browser sees it.
You're serving it a text/html which means that the browser sees it as HTML.
It needs to be served with an XML mime type such as application/xhtml+xml
i.e. like this
http://www.alohci.net/application/xhtml+xml/starov.htm.ashx
and not like this
http://www.alohci.net/text/html/starov.htm.ashx
Check the view source to see that it's the same file. Check the "Net" tab in firebug (or the equivalent for your browser) to see the content type in the response headers.
Also, you need to comment out the CDATA so it won't throw a parsing error when it's run:
<script>
//<![CDATA[
alert('Hey!');
//]]>
</script>
1) Comment your CDATA
//<![CDATA[
alert('Hey!');
//]]>
2) add a script type
<script type="text/javascript">

Disable page redirects using Greasemonkey

A website I wish to tweak is using window.location in order to redirect specific users to a blocking page. That website is doing it in plain <script> tag, so it is impossible to bypass it by overriding the onload event using document.body.setAttribute('onload','');.
Is there another way to inject my code to the page without using Firefox extensions such as NoScript?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
if (1) window.location="http://example.net"
</script>
</head>
<body></body>
</html>
This question is tagged "Greasemonkey", but GM cannot/will-not run your script before the redirect script fires. You'd have to write a firefox add-on to do that. Might poke around https://addons.mozilla.org/en-US/firefox/ first.
Sometimes you can use adblock to stop the load of the offending script.
NoScript might be the most cost-effective way, if the site's usable without javascript (although GM javascript will still run -- so you could replace lost functionality with GM code, maybe).
This question appears to be related to this one.

window.onload() is not firing with IE 8 in first shot

I am trying to make my pages work correctly with IE 8, I found out from here: http://www.masykur.web.id/post/How-to-Make-Our-Website-to-be-Ready-for-IE8.aspx
that, my page has to be XHTML 1.0 compliant and atleast CSS 2.1 compliant, I made my page and CSS compliant with only few warnings, but still window.onload() is not firing. Does anybody encountered this problem?
here is the code snippet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<title>Testing</title>
<link rel="stylesheet" href="test.css" type="text/css"></link>
<script type="text/javascript" src="login.js"></script>
<script type="text/javascript" src="common.js"></script>
<script type="text/javascript">
window.onload = function()
{
// Not coming here at all on first shot
}
</script>
</head>
<body>
.
.
.
However refreshing the page seems to make it work.
Am I missing something here?
UPDATE:
One of the IE addons created this problem, after disabling its working fine. Thanks for your time and answers :)
For IE try:
window.onload = new function() { alert('hello');};
This is a pretty old thread but I found a solution that might help others.
I was adding a function to window.onload via a dynamically injected script (really to mimic an external script load for reasons which are not important in this context). As stated in this post, on the first load within IE8, the window.onload would not fire, but all subsequent calls would.
I found out that if I put this in the HTML file as an internal script, it would work everytime:
var windowOnload = window.onload || function() {};
window.onload = function() { windowOnload(); };
All the above code does is "initializes" IE8's window.onload unobtrusively. I suspect that IE8 fails to trigger window.onload the first time if it is called from an external script as the onload event isn't attached yet to window (or in tech terms, its typeof is undefined). It seems that the first time that's what IE8 is doing: attaching onload to window without executing it properly.
The above code then becomes quite obvious: We are merely forcing IE8 to recognize the onload event. We don't care what gets executed, or what doesn't, so we simply make sure to pipe on through any existing window.onload code that is already defined (just as a precaution).
It is important to have this as an internal script to the HTML (at least from my testing).
Your HTML would thus look something like this (the relevant parts):
<script type="text/javascript">
var windowOnload=window.onload||function(){};window.onload=function(){windowOnload();};
</script>
<script type="text/javascript" src="script.js">
</script>
From my testing, after clearing cache, and reloading the page, I have gotten window.onload to successfully trigger each time.
I hope this helps.
You could have an error in your JavaScript's, if that happens, any JavaScript after that will not function correctly.
Try to remove the reference to login.js and common.js and try an alert within your problematic function.
I don't have IE8 to personally test, but what does this test do?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test IE 8</title>
<script type="text/javascript">
/* <![CDATA[ */
window.onload = function(){alert('Good morning!');}
/* ]]> */
</script>
</head>
<body>
<h1>Hello</h1>
<body>
</html>
If this test works as expected, try the CDATA bit around your internal JavaScript block.
And then, if that does not work as expected, there is probably something in the external JavaScript above it that prevents your onload from firing. The previous poster mentioned this. At that point, try your error console or debugger to point the way.
onload fires after ALL your content has loaded (including external images etc). It's possible those resources are taking a long time to load on the first go (before they are cached). Another possibility is an error in your code that only affects IE as is stopping your scripts (but only the first time is odd).
If you are getting different results using Apache vs. another web server (IIS?) and comparing the end result using IE8, then the differrence must be in the content type header being sent. Get the wget utility for your platform and see the headers that are produced. If you are on Windows, then the Portable Apps version of the GUI wget is pretty nice.
The following code works for me. When I load the page in Firefox I see the alert instantly. When I first load the page in IE 8 it warns me about active content. If I allow the blocked content it asks me to confirm, which I do. Then the alert appears as expected. If this does not work for you, try IE 8 on a different computer or start eliminating code in your page to check for errors. You could do a binary search: comment out the first half of the page and see if the alert appears; if it still does not, then uncomment out the first half and comment out the second half. Repeat as needed until you've narrowed it down to the offending code. Incidentally you don't need XHTML for IE8 compliance. HTML works fine and actually has some advantages.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
window.onload=function() { alert('hello');};
</script>
</head>
<body>
</body>
</html>
I know this is kinda old question, but I just faced the same thing.
window.onload=function() { alert('hello');};
is treated differently than
window.onload= new function() { alert('hello');};
The keyword here is new.
My JS was terminating whenever it reaches (onload=) part until I added the word'new' before 'function'. Even though it worked fine without 'new' in my localhost, but once I put it online, it doesn't work until I add 'new'.
Old question but I had the same issue but it turned out to be another problem. My problem was that I did <script type="application/javascript"> which <IE9 does not understand or try to run even. For it to work for older browsers you still have to use text/javascript even though this isn't technically the correct type...

Download Javascript generated XML in IE6

I'd like to use Javascript to make IE6 download a file. It'll be created on the fly using Javascript. This file doesn't exist on a webserver. Here's a small example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function clicked() {
var xml = "<data>Just for testing</data>";
document.open("text/xml", "replace");
document.write(xml);
}
</script>
</head>
<body>
<input type="button" value="Download" onclick="clicked();" />
</body>
</html>
Instead of loading the xml in the browser window, I want it to cause IE6 to prompt the user where to download the data to so that it can be saved without them having to use File -> Save as. Any ideas?
For IE6 you should be able to use document.execCommand() after your document.write():
document.execCommand('SaveAs',true,'file.xml');
This is not part of any standard and will only work in IE flavor browsers.
If your data must be generated client side, then you can post it back to the server so that it can be returned as a downloadable file.
No, this is not possible. A web-browser strictly doesn't allow this, as the ability to save files to disk through JavaScript only, would be very dangerous, even if the confirmation popup shows up.
EDIT: Thanks to other answers, I found out (not surprisingly) that this behavior is possible with some versione of IE.

Categories

Resources