HTML with commented JavaScript code - javascript

I am trying to parse a HTML code in order to extract all links in it. To avoid unavailable links I remove the commented code that begins with <!-- and ends with --> .Here comes the problem: In the HTML code I may find some JavaScript code, for example:
<html>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
if (document.images) {
var pic2 = new Image(); // for the inactive image
pic2.src = "pic2.jpg";
var title2 = new Image();
title2.src = "title2.jpg";
}
...
-->
and the weird thing is that the js code is commented but it still works. So, if I remove that code, the result won't be as expected. What should I do in order to identify when I'm facing with unused commented code and when that commented code is functional?

the weird thing is that the js code is commented but it still works
Those aren't comments. Is is just syntax allowed inside script (and style) elements that follows the comment syntax so that browsers which predate script and style don't render the code as text.
What should I do in order to identify when I'm facing with unused commented code and when that commented code is functional?
Write a real HTML parser, following the parsing specification, and then remove any comment nodes from the generated DOM.
As a dirty (but possibly quick) solution, you could just ignore comments inside elements marked as containing CDATA in the HTML 4.01 DTD.

the weird thing is that the js code is commented but it still works
There is nothing weird about it. The comments <!-- --> only work in HTML, not JavaScript. Your above code will still work since you've put these comments within the <script> tags.
The only difference it makes is that if the user has disabled JavaScript on his/her browser, he won't see the code printed on the browser (since HTML will parse those comments in the absence of JavaScript).

You need to comment out the whole <script> block. e.g.
<!-- <script>
...some javascript code...
</script> -->

Related

Using JavaScript to insert last updated date in HTML

Dreamweaver can generate the attached codes in JavaScript so that users can record the last updated date in a webpage.
The instruction works fine inside DW but it was skipped by most browsers as comments.
Placing the codes inside the "&lt script language = javascript &gt ... &lt /script &gt" markup does not help.
Anoter unsuccessful thing that I have tried is just to strip off the comment signs. It seems the syntax/format is not correct.
Pls help.
<!-- #BeginDate format:It1 -->14-10-2021<!-- #EndDate -->

Unknown Errors in Script

I'm trying to make a HTML/JS/CSS script that counts the number of days until some birthdays.
Last year, I made one, it still works, I copied and pasted the same script, and changed the names/dates and now it doesn't work.
Working one: http://jsbin.com/iFItOYo/16/edit
Broken one: http://jsbin.com/iFItOYo/14/edit
You made a couple of mistakes:
You forgot the closing bracket at this point:
fatima = new Date(thisYr,2,7)
if (fatima.getTime() < now.getTime()) {
fatima.setYear(nextYr)
} <-- this one is missing
In the beginning you state now = new Date, which should be now = new Date()
You forgot to close the <!-- that you begin in the top of your code
It's quite simple, you are missing the the closing tag of the comment '-->', and thus you get an unexpected end of input error.
Also putting your script inside of a comment is not such a good practice, use cross browser CSS if comments
Also, use indenting, and lower case HTML, with indenting as well.
In addition, your script tag is not valid in any HTML \ XHTML spec.
Hope this helps.
Another issue:
<SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT"> which comes after the h3 opening tag is also missing.
Perhaps this question belongs to code review.
You deleted the <script ...> tag right after the opening <body> tag.
There is a lot of mistakes in your code. You should do something to view it clearly so that you can see your mistake easily like indent code, write all in lowercase (both javascript and html), comment and closing code more exactly...
To fix the one not run you must do these 3 points:
1 Like koenp answer, closing this :
falisha = new Date(thisYr,2,20)
if (falisha.getTime() < now.getTime()) {
falisha.setYear(nextYr)
} <== add this bracket
2 Missing the script tag before calling the document write function in body
<H3>The following are the numbers of days until class birthdays (2011-12):
<SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT"> <== add this
3 Wrong variable in this line
if (anahi.getTime() < now.getTime()) {
anihi.setYear(nextYr) <== change it to anahi (of course)
}

How to re-apply prettyPrint AFTER run_prettify.js has been loaded

I'm trying with Javascript code prettifier, and come up with a question.
If I do not assign class="prettyprint" to <pre> in static html, but wish to apply prettyprint later(e.g, when user click on a "colorize" button on my webpage), how can I achieve this?
Slightly modifying original run_prettify.js or prettify.js is acceptable, because I'm going to put this to offline use.
My experiment:
Writing try-delay-class.html:
<html>
<head>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
</head>
See it:
<pre>
class Voila {
public:
// Voila
static const string VOILA = "Voila";
// will not interfere with embedded tags.
}
</pre>
</html>
Open in Chrome v26, bring up the console, execute:
pres=document.getElementsByTagName('pre')
pres[0].className+=" prettyprint"
Syntax color does not come up.
According to a comment found here, How to get prettyprint to work on dynamically generated dom element , I find the way out. Just call:
PR.prettyPrint()
BTW: If you want to remove code color highlight, you cannot simply set pre's class to empty followed by PR.prettyPrint() again. PR.prettyPrint() can only attach color tags but not remove them. A feasible way to do that is saving your original <pre> content before applying prettyprint, then restore <pre>s content later. Verified in my post jQuery, how to clone back saved elements? .
You can find three examples here
I did it as follows in js:
document.getElementById('outputa').innerHTML =
PR.prettyPrintOne("your code in brackets or your variable (without these brackets)",
'java');

what happens when you use javascript to insert a javascript widget?

can anyone explain what happens when you use javascript to insert a javascript based widget?
here's my js code:
var para = document.getElementsByTagName("p");
var cg = document.createElement("div");
cg.setAttribute("class", "twt");
cg.innerHTML='<a href="http://twitter.com/share" class="twitter-share-button"
data-count="vertical" data-via="xah_lee">Tweet</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
document.body.insertBefore(cg, para[1]);
it inserts the twitter widget, before the first paragraph. As you can see above, the twitter widget calls for a javascript that shows how many time the page has been tweeted.
doesn't work in Firefox, Chrome, but semi-works in IE8. What should be the expected behavior when this happens? Does the newly inserted js code supposed to execute? If so, how's it differ from if the code is on the page itself?
In order to execute the JS code you insert into a DIV via innerHTML, you need to do something like the following (courtesy of Yuriy Fuksenko at http://www.coderanch.com/t/117983/HTML-JavaScript/Execute-JavaScript-function-present-HTML )
function setAndExecute(divId, innerHTML) {
var div = document.getElementById(divId);
div.innerHTML = innerHTML;
var x = div.getElementsByTagName("script");
for (var i=0;i<x.length;i++) {
eval(x[i].text);
}
}
A slightly more advanced approach is here: http://zeta-puppis.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/ - look for <script> tags, take their conĀ­tent and create a new eleĀ­ment into the <head>.
innerHTML does not work to insert script tags (because the linked script, in most browsers, will fail to execute). Really, you should insert the script tag once on the server side and insert only the link at the location of each post (that is, if you are adding this to a blog home page that shows multiple posts, each with their own URLs).
If, for some reason, you decide that you must use one snippet of JavaScript to do it all, at least import the tweet button script in a way that will work, for example, the Google Analytics way or the MediaWiki way (look for the importScriptURI function). (Note that I do not know the specifics of the tweet button, so it might not even work.)

Injecting JavaScript into head element of website using Fiddler

I was thinking of using Fiddler for the following purpose...
I have a JavaScript based service I want to demonstrate to potential clients. In order to show them what their website could look like if they install (i.e. include) my script, I want to set up Fiddler on my PC, so that when fetching the client's website, the
<script type="text/JavaScript" src="myscript.js"></script>
line will be included in the HTML <head> section.
Can this be easily done with Fiddler? Could someone point me to where I may find the documentation covering that, if it is?
Thanks!
----Update----
For the time being I have resorted to using a BHO to add my script to the page. I use execScript(), upon onDocumentComplete, to run a simple piece of JavaScript which appends the .js file I need to the page. But EricLaw's pointers and jitter's answer seem like the way to go for a more complete (and elegant) way to do what I need.
If someone is interested I could upload the BHO code here.
-Thanks!
Open fiddler -> Menu Rules -> Customize Rules (or hit Ctrl+R)
The CustomRule.js file opens. Scroll down until you find the line
static function OnBeforeResponse(oSession: Session)
This is where your code goes. Here you can change the server response before the browser sees it.
The following code sample shows how to include a custom piece of jQuery code which replaces the Unanswered link in the horizontal menu with a link which serves as short cut to Unanswered jQuery Questions
I first show you the jQuery code I want to include
<script type='text/javascript'>
$(function() {
var newLink = 'Unanswered jQuery';
$('div#hmenus div.nav:first ul li:last a').replaceWith(newLink);
});
</script>
Now the fiddler code (based on code found in CustomRules.js and code samples from the FiddlerScript CookBook)
//is it a html-response and is it from stackoverflow.com
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.HostnameIs("stackoverflow.com")) {
// Remove any compression or chunking
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
// Match the jQuery script tag
var oRegEx = /(<script[^>]*jquery.min.js"><\/script>)/gi;
// replace the script tag withitself (no change) + append custom script tag
oBody = oBody.replace(oRegEx, "$1<script type='text/javascript'>$(function() {$('div#hmenus div.nav:first ul li:last a').replaceWith('Unanswered jQuery');})</script>");
// Set the response body to the changed body string
oSession.utilSetResponseBody(oBody);
}
I think you should now able to hackyourself together a piece of code which fits your problem.
Example
// Match the head end
var oRegEx = /(<\/head>)/gi;
// replace with new script
oBody = oBody.replace(oRegEx, "<script type='text/javascript' src='http://url/myscript.js'></script>$1");
if you use jQuery you can add js on the fly. I would probably think you can have a method which would include/exclude your script based on some query param. This is how you would include JS with jQuery
$.getScript('someScript.js',function(){
//Do something here after your script loads
});
Haven't tried it, but how about GreaseMonkey for IE?

Categories

Resources