java script error with document.write() - javascript

I am new to javascript and trying to execute the following code, could anyone tell me why only first document.write is being executed not the other ones.
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>my first java script</title>
</head>
<body>
<script type="text/javascript">
var myhello="hello world, welcome to java script";
var heading="a page of java script";
var linktag="wanna search on google";
var redtext="<span style=\"color:red\">I am so colorful today!</span>";
var begineffect="<strong>";
var endeffect="</strong>";
var beginpara="<p>";
var endpara="</p>";
document.write(begineffect+heading+endeffect);
document.write(begingpara);
document.write(hello);
document.write(endpara);
document.write(begingpara);
document.write(linktag);
document.write(endpara);
document.write(beginpara);
document.write(redtext);
document.write(endpara);
</script>
</body>
</html>
I have tested the following code in all web browser.

It is generating an error because you don't have a variable called hello
var hello = 'define something here';
document.write(hello);
Using a good browser like chrome, or firefox+firebug will reveal errors like this if you use the web inspector.
http://www.google.com/chrome/intl/en/webmasters-faq.html#jsexec

If you check your console (F12 in Chrome, or load Firebug for Firefox) you see this error:
Uncaught ReferenceError: begingpara is not defined
You have many typos and incorrect variable names (i.e. you have defined variables but used a different name when referencing them) - correct them and your code will run.

It overwrites everything so the others no longer exist

Related

DOM Based Cross-site Scripting example: Java Script does not get executed

I have recently read the following article about a DOM-based XSS:
https://www.netsparker.com/blog/web-security/dom-based-cross-site-scripting-vulnerability/
But the examples provided in the article are not working as described. I created the HTML example file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head></head>
<body>
<script>
document.write("<b>Current URL</b> : " + document.baseURI);
</script>
<h1> Welcome on my Example Page </h1>
</body>
</html>
I have put the above file in an application folder of a Web-Application deployed on the JBoss server and I have called the resource from my browser ( I have tried both IE 11 and Firefox). IE 11 shows the resulting HTML content like this:
Current URL : undefined
Welcome on my Example Page
while Firefox shows the resulting HTML content like this:
Current URL : https://localhost:8443/ukvlei/example.html
Welcome on my Example Page
In both cases, I can not force any of the browsers to execute the java script function after the # sign, as described in the article. When I type
https://localhost:8443/ukvlei/example.html#<script>alert(1)</script>
in the address bar of the browser, I get the following HTML content:
under IE 11:
Current URL : undefined
Welcome on my Example Page
under Firefox:
Current URL : https://localhost:8443/ukvlei/example.html#%3Cscript%3Ealert(1)%3C/script%3E
Welcome on my Example Page
What am I doing wrong, so that I cannot execute the java script in any of the browsers?
Thank you!
You haven't run the URI through decodeURIComponent so that the URI syntax is converted back to text.
I want to thank both #scagood and #Quentin, with whose help I got my question answered. So, the answer is:
1.) Apperantly the provided example in the article is out of date, as it is around three years old, so:
2.) Use window.location.href instead of document.baseURI;
3.) To make the example run both under IE and Firefox, decode the URL using decodeURIComponent.
So, the working example HTML file now looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head></head>
<body>
<script>
document.write("<b>Current URL</b> : " + decodeURIComponent(window.location.href));
</script>
<h1> Welcome on my Example Page </h1>
</body>
</html>

Embedding JS and HTML at the same time fails

I would like to have many HTML pages of one type, the only difference being the page title and some data stored in different .json files. Everything else should be stored in two centralized files, a .js and an .html file. In pseudocode the pages should look like this:
<html>
<head>
include global_script.js
include specific_data_n.json
</head>
<body>
include global_body.html
</body>
</html>
where the n-th page includes the data file specific_data_n.json but everything else is always the same.
I know how to include .js and .json files in the header. However, I don't really know how to include the .html file in the body. I searched on the net and, in particular, found this question: Server side includes alternative I tried different ways of including the body proposed in the answers but whatever I tried, I got a JS error.
Here is a minimal example of the problem. First, the working file where the body is in the main file and not in an extra file:
function init(){document.getElementById('demo').innerHTML = '2+2=4';}
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><head>
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<div id="demo">
2+2=5
</div>
</body>
</html>
Now I tried to put the body in an external file following one of the answers of the question linked above.
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<!-- Content, inclusion from https://stackoverflow.com/questions/35249827/can-you-link-to-an-html-file -->
<div w3-include-html="body_minimal.html"></div>
<script>
(function () {
myHTMLInclude();
function myHTMLInclude() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
myHTMLInclude();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
})();
</script>
</body>
</html>
and the body_minimal.html which is included:
<div id="demo">
2+2=5
</div>
I also tried different further approaches for embedding the body_minimal.html file (which I can present if needed) but none of them works, so I assume that it is some fundamental problem. I always get the error in the JS debugger:
TypeError: document.getElementById(...) is null
I need to add that I have no experience neither in HTML nor in CSS and am mostly copy&pasting stuff from different tutorials, forums and Q&A sites so I do not really understand what this code for the embedding of the HTML file is doing. :)
Thanks for any hint on what the problem might be and a happy new year!
This really belongs as a comment but unfortunately my account is new so I'm not allowed...An answer will have to do.
If your webhost runs PHP I'd suggest looking into PHP includes, they're much simpler.
Basically, you would save your central html file as a .php file instead and include the HTML file you want using
<?php
include 'global_body.html';
?>
Found a solution which looks stupid, but as you know, if something looks stupid but works, it isn't stupid. :) I just made another .js file which writes the body contents via document.write():
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript" src="body.js"></script>
</body>
</html>
And the included .js files:
//body.js
document.write('<div id="demo"->2+2=5</div>');
and
//script.js
document.getElementById('demo').innerHTML = '2+2=4';
The only problem is that in a real world scenario the contents of the body are many lines and JS needs a backslash on each line break. Also, the syntax highlighting only shows all the HTML code in one colour as from JS's point of view it is just a string. Therefore I'm still interested in better/cleaner solutions!

JavaScript exit popup function doesn't work properly in Chrome and IE

I have an exit popup js function which displays an alert and adds something to the url (and redirects) when someone tries to leave the page.
The alert is displayed in all browsers but the code:
window.location.href = "?p=exit"
is not executed in Chrome and IE.
It works fine in Firefox. When you reload the page an alert is displayed and the url is modified.
Take a look at the source code, it is very simple.
Code:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var exit=true;
function confirmExit()
{
if(exit)
{
window.location.href = "?p=exit";
}
if(exit)
return "Wait! Don't Leave Empty Handed!\n\nThank you for taking the time to check out our offer! Before you go we have a complimentary crash to help you succeed. Click the 'Cancel' or 'Stay On This Page' button if you're interested!";
}
</script>
</head>
<body onbeforeunload="return confirmExit()">
</body>
</html>
You cannot (cross-browser) redirect from "onbeforeunload".
Chrome blocks alerts set in "onbeforeunload".
Check out this answer for more information:
https://stackoverflow.com/a/7080331/353710

Why does appending a <script> to a dynamically created <iframe> seem to run the script in the parent page?

I'm attempting to create an <iframe> using JavaScript, then append a <script> element to that <iframe>, which I want to run in the context of the <iframe>d document.
Unfortunately, it seems I'm doing something wrong - my JavaScript appears to execute successfully, but the context of the <script> is the parent page, not the <iframe>d document. I also get a 301 Error in Firebug's "Net" tab when the browser requests iframe_test.js, though it then requests it again (not sure why?) successfully.
This is the code I'm using (live demo at http://onespot.wsj.com/static/iframe_test.html):
iframe_test.html
<!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="text/html; charset=utf-8"/>
<title><iframe> test</title>
</head>
<body>
<div id="bucket"></div>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#bucket').append('<iframe id="test"></iframe>');
setTimeout(function() {
var iframe_body = $('#test').contents().find('body');
iframe_body.append('<scr' + 'ipt type="text/javascript" src="http://onespot.wsj.com/static/iframe_test.js"></scr' + 'ipt>');
}, 100);
});
</script>
</body>
</html>
iframe_test.js
$(function() {
var test = '<p>Shouldn\'t this be inside the <iframe>?</p>';
$('body').append(test);
});
One thing that seems unusual is that the the code in iframe_test.js even works; I haven't loaded jQuery in the <iframe> itself, only in the parent document. That seems like a clue to me, but I can't figure out what it means.
Any ideas, suggestions, etc. would be much appreciated!
Had the same problem, took me hours to find the solution.
You just need to create the script's object using the iframe's document.
var myIframe = document.getElementById("myIframeId");
var script = myIframe.contentWindow.document.createElement("script");
script.type = "text/javascript";
script.src = src;
myIframe.contentWindow.document.body.appendChild(script);
Works like a charm!
I didn't find an answer to my original question, but I did find another approach that works even better (at least for my purposes).
This doesn't use jQuery on the parent page (which is actually a good thing, as I'd prefer not to load it there), but it does load jQuery in the <iframe> in an apparently completely valid and usable way. All I'm doing is writing over the <iframe>'s document object with a new one created from scratch. This allows me to simply include a <script> element in a string which I then write to the <iframe>'s document object.
The code:
<!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="text/html; charset=utf-8"/>
<title>frame</title>
</head>
<body>
<div id="test"></div>
<script type="text/javascript">
// create a new <iframe> element
var iframe = document.createElement('iframe');
// append the new element to the <div id="bucket"></div>
var bucket = document.getElementById('test');
bucket.appendChild(iframe);
// create a string to use as a new document object
var val = '<scr' + 'ipt type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></scr' + 'ipt>';
val += '<scr' + 'ipt type="text/javascript"> $(function() { $("body").append("<h1>It works!</h1>"); }); </scr' + 'ipt>';
// get a handle on the <iframe>d document (in a cross-browser way)
var doc = iframe.contentWindow || iframe.contentDocument;
if (doc.document) {
doc = doc.document;
}
// open, write content to, and close the document
doc.open();
doc.write(val);
doc.close();
</script>
</body>
</html>
I hope this helps someone down the road!
The answer to the original question is simple - the execution of the script is done by jquery, and since jquery is loaded in the top frame, this is where the script runs too, no matter where you are appending it. A smarter implementation of jquery can no doubt be made to use the correct window object, but for now things are how they are.
As to the workarounds, you already have two good answers (even if one is your own). What I might add is that you can use one of those workarounds to include jquery.js in the iframe, and then get that jquery object instead of the top one to insert your additional markup... but that may very well be overkill too.

Issues with most basic e4x test

When I load a page containing e4x in FF 3.5, I get no inkling that e4x even exists in the browser's JS implementation. Notes below, but here's my HTML :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>e4x test</title>
<script type="text/javascript" src="lib/dojo/dojo/dojo.js">
</script>
<script type="text/javascript;e4x=1">
function hello() {
var x = new XML();
x = <foo></foo>
dojo.byId("container").innerHTML = "Print me!" + x.toXMLString();
}
</script>
<script type="text/javascript">
dojo.addOnLoad(hello);
</script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
When I inspect in firebug, it says x doesn't have a toString() method, and my IDE (aptana) thinks that XML is not an object type. Does anyone have any idea what I'm doing wrong?
I'm guessing that it was working all along, but your browser doesn't recognize a "foo" tag and because it does not know how to render it, it ignores it. By putting something inside of your foo tag you would get content out.
BTW: The new XML() statement is entirely unnecessary. You can just do this:
var x = <foo>bar</foo>;
That will create a new XML object for you. Saying new XML() is like saying new String(). You can do it, but it is just a waste of space.
It turns out that I need more in the XML for it to print anything out. bar works, for example. I'm not sure why, but that is what fixed it!

Categories