Hiding JavaScript from displaying in old browsers - javascript

I am trying to learn JavaScript from a book. The first chapter of the book says to use the following format to support older browsers that don't support JS. What it actually does is simple, it uses HTML comment tag to hide script from browsers that don't support JS. My doubt here is this code works fine for me in all the browsers but is showing error in Aptana Studio 3. Now I understand that the error is due to Aptana considering "<" as a relational operator but how can I resolve this error?
<script>
<!--
//some JS code over here...
//-->
</script>
Error(Syntax Error: Unexpected Token) coming at :
<!--

I'm aware that this does not answer your question directly, but the truth is that this simply does not need to be done. If a browser does not know how to interpret the JavaScript, almost all browsers will ignore the code anyway. Furthermore, adding the <!-- // --> can be dangerous as well for the following reasons, given by Matt Kruse:
Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
It is not allowed within HTML comments, so any decrement operations in script are invalid
For a more detailed explanation, I recommend you check out this documentation about the best practices for JavaScript and this question that explains why using HTML comments in JavaScript is bad practice.
If for whatever reason you still want to show content to the user if they have JavaScript disabled (or can't run it because of an old browser), use a <noscript> tag
If you truly are deadset on commenting out your JavaScript then use this code snippet instead, which shouldn't give you the error:
//<!--
//-->
If you have any more questions feel free to ask.

Every browser now supports JS. This trick was used to prevent the first generation browsers from showing JS code as plain text.
You may wanna take a look at this article.
Do not use the <!-- //--> hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years. <!-- //--> is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include --, so a script that decrements has an HTML error.
Edit 1:
If you still wanna use this trick in Aptana Studio 3 try commenting the first part too:
<script>
//<--
Code Goes Here...
//--!>
</script>
I didn't test but solved the error in aptana

Related

How to bring back Javascript syntax error detection in Visual Studio Code

Take the following sample of HTML.
<html>
<head>
<script>
var myArr = ['thing1' thing2'];
</script>
</head>
<body>
</body>
</html>
If you're perceptive, you'll notice that I forgot to put a comma between the two array values inside of the script. This will, of course, cause any browser to fail to parse it and the whole script tag will not run. In previous versions of Code, this would be noted with a red underline, but it seems like in recent versions support has moved to plugins. They recommend installing the JSHint plugin to catch some issues, but I have a .jshintrc file in my project directory, with very few entries (to try to use mostly defaults) and while it catches "recommendations", it's still not catching actual syntax issues that break the scripts entirely. I'm also not sure it's doing anything for JavaScript it sees inside of a <script> tag (which I currently use to do quick tests or examples of features). It highlights keywords, but doesn't check syntax or anything.
Is there any configuration I can apply to Code, or my project, to get back this behavior?
The catching of actual syntax issues has been delegated to the Salsa interpreter within Visual Studio. Maybe this is a bug? However, for the other point you made about quick-checking code within script tags, as of the v0.10.10 Feb 2016 release notes:
There is no longer support for IntelliSense in script sections inside HTML documents.

How can I get the result from the JavaScript html page using HtmlUnit?

I'm now working on using a JavaScript html to do some tests. And I want to use HtmlUnit to access the page to acquire the running results on the JavaScript webpage.
And this page is here(for the page source, you can right-click mouse to see the source):
http://itec.hust.edu.cn/~zhangcw/javascript.html
what I want is to get the running result about the delay value "delay:xxx ms" calculated by
the JavaScript on that page. However, when I use HtmlUnit to capture the html, it always capture the original source of that page and doesn't contain the running result. My code is like this:
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://itec.hust.edu.cn/~zhangcw/javascript.html");
String source = page.asXml();
System.out.println(Source);
The source only contains the JavaScript source codes and html content, not the execution result by the JavaScript on the page. What I should do using HtmlUnit?
My Question is how can I use the HtmlUnit to get the JavaScript running result on the page?
Thanks for reading the text, tough for my English skill.
HtmlUnit has a JavaScript engine that is very sensitive to syntactical errors. So the fact that something works in a normal browser (Chrome, IE, FF, etc) doesn't mean that it will work on HtmlUnit.
I took a very quick look at the code and detected too many syntactical errors. I even run this through the w3c validator and found 10 errors. Here is just one example:
<button type="button style="
You're clearly missing a quote there.
And also some errors that the validator might not detect such as:
<text id= _delay>
You are missing the quotes and you have an extra space.
Finally, the most likely reason why the code is not working is that you defined it as HTML 4.01 Transitional and you added the HTML5 attribute onerror to the image. Furthermore, you've added a piece of JavaScript to that attribute and it happens to be the JavaScript that is not executing.
Fixing errors might help. However, it doesn't necessarily mean it will work after that.

How to make JSHint warn when HTML tags are included in JavaScript code?

In our dev shop, we use client-side templates and include no HTML tags in our JavaScript code.
In our continuous integration process, we run JSHint automatically after every commit (post-build action in Jenkins) to verify compliance with our coding style guidelines.
I'd like to configure JSHint so it throws a warning when it finds an HTML tag in a .js file.
How can I accomplish this? I've searched, but I can find no examples of HTML tag warnings nor custom rules for JSHint.
Edit:
Just to be clear, I'm trying to catch code like this:
var newDiv = "<div>Hello World!</div>";
$("body").append(newDiv);
If I could get JSHint to produce a warning for the first line in the example above, that'd be fantastic.
Second Edit:
If there's post-build plugin for Jenkins that could throw a validation error if HTML is found in a .js file, then that'd also be a great alternative solution.
The Answer
No, jSHint does not support disallowing arbitrary string contents or HTML tags inside of strings. It also does not support custom rules, for now, though the author has discussed adding a public api in the future.
My speculation (as I am not an insider) on WHY
The solution you're proposing (disallowing any HTML tags in any scenario) would disallow a wide variety of highly valid use cases, regardless of how you feel about creating HTML in js. I understand that it is what your team wants to do, but such a blunt force rule is not going to have the general applicability of the rest of jsHints rules. Their focus is on enforcing style rules. Since you're disallowing all HTML tags in strings this is really more of a content validation than a style one. It would eliminate the following content examples, which are irrelevant to DOM injection/separation of concerns.
For instance:
var example="I'm writing a report on <div> tags and css";
or
var htmlStrippedText = text.replace("<div>","");
My Advice
Of course lack of broad applicability is not a reason for YOU not to do this. If you really want to filter content like this, use a command line script to search with a regex. Since you only want to see if there is HTML, not whether its valid, you can just search for stuff in the form <[div|span|body|html... as well as document.createElementand it should be fine (although you might have to be more creative if you want to allow it inside of comments). Just don't use nodejs to run your script with JS or it will fail to validate itself. :)
Of course none of this will stop a determined developer:
var topSecretDOMObject,topSecretFunction,topSecretArgument;
topSecretFunction = "create"+"Element";
topSecretArgument = "d" + "i" + "v";
topSecretDOMObject = document[topSecretFunction](topSecretArgument);

Why does a JS script placed after the </body> and </header> get executed?

I was working on something in PHP and I wanted to include a file and insert something at the end. Without thinking about it, I did the include and then echoed out the material I wanted to insert, which was a JS script.
When I looked at the output, I realized I had forgotten about the tags in the included file. The script was inserted after them, but surprisingly (at least to me) it was executed.
Had you asked me before I did this if a script after the and tags would execute, I would have said "I don't think so." I would have said that I thought it would not execute because I had assumed, up to now that anything after the and tags is ignored by browsers.
So, had you asked, I would have given that answer and I would have been quite wrong.
A script placed after the and tags does execute - why?
I've tried it with FF 3.6.24 and I.E 8.0.7601.17514 and it behaves the same in both.
Any text after the and tags is displayed - why?
Does anyone have any thoughts on this? And, is this something I might be able to rely upon? If so, I can simplify some processing, here and there.
Here's the page I was playing with http://www.bobnovell.com/PastHtmlEndTesting.shtml - let me know if your particular browser does not execute the script and/or display the text that I've put after the script.
Bob
This is well specified behavior in HTML5 though it will be flagged by an HTML5 validator.
The after after body insertion mode defines what happens to content that is after the </html> tag. The rule that handles this case is:
Anything else
↪ Parse error. Switch the insertion mode to "in body" and reprocess the token.
So techinically, it's a parse error, but one with well defined behavior. The <script> element is parsed and executed as if it had appeared in the body, and the element should appear in the DOM in the body.
Most browsers will not treat "parse errors" as fatal. The HTML 5 spec explains:
Certain points in the parsing algorithm are said to be parse errors. The error handling for parse errors is well-defined: user agents must either act as described below when encountering such problems, or must abort processing at the first error that they encounter for which they do not wish to apply the rules described below.

IE Operation Aborted - None of the regular fixes work

First of all, I've been researching this "Operation Aborted" error / bug for what seems like weeks, so here are a couple related questions and good articles if you are not familiar with it:
Why does ASP.NET cause the “Operation Aborted” Error in IE7? (so question)
Detecting cause of IE’s Operation Aborted Issue (so question)
Official Microsoft Knowledge base
Official IE Blog
Now here's my problem:
First I tried moving all my <script> elements to the end of my body tag. Didn't work. Then I refactored all my js functions to an external file that is linked in the <head>, all of my js functions are called from onclick or onkeypress anyway. Still getting the error. The last line of one of my .js files is
document.onload = setTimeout("foo()",500);
so I moved that to <body onload="setTimeout('foo()',500);">. I'm still getting this error. I don't know what to do. The only place I'm editing DOM elements is in foo(). Please help!
About my setup:
Java, Hibernate, Struts, JSPs ... I think that's all that is relevant.
What am I missing here?
Thanks in advance.
There are several causes for this. Two of the most common are:
1) scripts attempting to modify the DOM before the document has completely loaded
2) Trailing commas in object or array declarations
Number two is usually relatively easy to find, while number one is much tougher. Generally the best way to track down IE Javascript problems is to install Microsoft Script Debugger, so at least you can see what lines are causing the problem. With Script Debugger, IE will halt execution inside the browser and kick the script to a Script Debugger console, which will show the problem line. Much more informative than regular IE error messages.
Please see my answer to this question in another thread. I love this little trick and it has never failed me (when the cause is DOM manipulation before IE is ready, I mean). And as written, it doesn't affect the DOM-compliant browsers.
That problem can be a bear on a large page. Beyond the advice in the articles you already have, the only thing I can suggest from here is to remove wide swaths of the page in a dev environment until the problem goes away. Keep refining what is/is not on the page until you know which piece of content is causing the problem.
I've actually seen a confluence between two unrelated page elements cause this problem. I don't remember excisely why but the above approach, although painstaking, still worked.

Categories

Resources