Replace complete HTML document with HTML code containing inline scripts - javascript

I have the following code which works properly in chome
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
//<![CDATA[
!function (){
window.stop();
var html = '<!DOCTYPE html>\n<html>\n<head>\n <meta charset="utf-8">\n</head>\n<body>\n \<script>console.log("loaded");<\/script>\ntext\n</body>\n</html>';
document.documentElement.innerHTML = html;
}();
//]]>
</script>
</body>
</html>
It prints "loaded" in the console. The same code does not work by firefox, it does not run the script, just prints the text.
(If you are curious why I need this, you can find it here: https://stackoverflow.com/a/30933972/607033 )
I tried possible solutions like this: https://stackoverflow.com/a/20584396/607033 but they did not work. Any idea how to work this around?
Note: there are many scripts in the HTML, e.g. bootstrap, jquery, facebook, google, etc..., not just a single inline script.

I think there is no way in firefox to replace the complete HTML document with javascript without leaving the actual page. A workaround to reuse the original document and replace only the head and body tags:
$('html').html(html);
does this automatically: it strips out the HTML tags, injects the head and the body and loads the scripts.
ref: https://stackoverflow.com/a/1236372/607033

Related

Javascript Not Working in HTML - In a Variety of Ways

Is it possible to load javascript without jQuery? I spent the better portion of yesterday evening simply trying to create the most basic HTML page with working CSS and Javascript and - despite the numerous methods I have tried - none of them have worked. Here is my basic HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<div>On</div>
<input type="button" onclick="popup()" value="Click Me!">
</body>
</html>
This is being hosted locally on XAMPP, the page displays fine and the CSS works fine, the javascript is in the same directory as the html page and works fine when written inline with the HTML. However the js does not work in any of the following scenarios when trying to include it as an externality:
When application/javascript is used above it still doesn't work. All I receive in either case (in the Firebug script window) is "popup()" and that's it. Here is the script.js file:
function popup() {
alert("Hello World")
}
This js also doesn't work (I tried it even though I'm not parsing XML):
//<![CDATA[
function popup() {
alert("Hello World")
}
//]]>
nor this:
document.addEventListener('DOMContentReady', function popup() {
alert("Hello World")
})
nor this:
<script type="text/javascript">
function popup() {
alert("Hello World")
}
</script>
Not that I really expected it too, but I was getting desperate. If anyone knows what's going on, I'd appreciate any info.
I'm open to this being an issue with hosting this locally on XAMMP but find it doubtful as CSS and HTML are both flying. However the js works if I include it inline with the HTML(?). If it helps, when Firebug displays popup() in the script window it also shows an #conn1source connection.
UPDATE: according to one of the suggestions in the comments if I only write the following in the js file it works:
alert("Hello World")
however the function does not. So I'm guessing this means that I wrapped the function somehow incorrectly in the js file, but I'm following standard practice as far as I am aware.

Calling javascript script from html

I have a simple javascript file like so:
$(document).ready(function () {
alert("my controller");
});
I have an HTML file like so:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" src="/js/generateLineupController.js"></script>
</body>
</html>
for the love of all things holy why in the world would the alert not show? I get a 200 on GET for the javascript file, so it's loading.
Several problems here.
You're trying to load the script twice for some reason. Don't do that. Load it in <head>, or at the end of <body>, but not both.
You're trying to use jQuery syntax ($(...)), but you haven't loaded the jQuery library. You'll need that.
The $(document).ready(...) indicates that you are trying to use jQuery, but you aren't loading jQuery in your page. Check your console log; you will see the errors there.
Also, there's no need to load the script twice with two <script> tags; just load it once.

Is it possible to retrieve the *full* HTML page source of an iframe with Javascript?

I am trying to figure out how to retrieve the full (that means all data) HTML page source from an <iframe> whose src is from the same originating domain as the page that it is embedded on. I want the exact source code at any given time, which could be dynamic due to Javascript or php generating the <iframe> html output. This means AJAX calls like $.get() will not work for me as the page could have been modified via Javascript or generated uniquely based on the request time or mt_rand() in php. I have not been able to retrieve the exact <!DOCTYPE> declaration from my <iframe>.
I have been experimenting around and searching through Stack Overflow and have not found a solution that retrieves all of the page source including the <!DOCTYPE> declaration.
One of the answers in How do I get the entire page's HTML with jQuery? suggests that in order to retrieve the <!DOCTYPE> information, you need to construct this declaration manually, by retrieving the <iframe>'s document.doctype property and then adding all of the attributes to the <!DOCTYPE> declaration yourself. Is this really the only way to retrieve this information from the <iframe>'s HTML page source?
Here are some notable Stack Overflow posts that I have looked through and that this is not a duplicate of:
Javascript: Get current page CURRENT source
Get selected element's outer HTML
https://stackoverflow.com/questions/4612143/how-to-get-page-source-using-jquery
How do I get the entire page's HTML with jQuery?
Jquery: get all html source of a page but excluding some #ids
jQuery: Get HTML including the selector?
Here is some of my local test code that illustrates my best attempt so far, which only retrieves the data within and including the <iframe>'s <html> tag:
main.html
<html>
<head>
<title>Testing with iframe</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function test() {
var doc = document.getElementById('iframe-source').contentWindow.document;
var html = $('html', doc).clone().wrap('<p>').parent().html();
$('#output').val(html);
}
</script>
</head>
<body>
<textarea id="output"></textarea>
<iframe id="iframe-source" src="iframe.html" onload="javascript:test()"></iframe>
</body>
</html>
iframe.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html class="html-tag-class">
<head class="head-tag-class">
<title>iframe Testing</title>
</head>
<body class="body-tag-class">
<h2>Testing header tag</h2>
<p>This is <strong>very</strong> exciting</p>
</body>
</html>
And here is a screenshot of these files run together in Google Chrome version 27.0.1453.110 m:
Summary
As you can see, Google Chrome's Inspect element shows that within the <iframe> the <!DOCTYPE> declaration is present, so how can I retrieve this data with the page source? This question also applies to any other declarations or other tags that are not contained within the <html> tags.
Any help or advice on retrieving this full page source code via Javascript would be greatly appreciated.
Here is a way to build it from the doctype, seems to work for html 4 and 5, I didn't test for stuff like svg.
<html>
<head>
<title>Testing with iframe</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function test() {
var d = document.getElementById('iframe-source').contentWindow.document;
var t = d.docType;
$('#output').val(
"<!DOCTYPE "+t.name+
(t.publicId? (" PUBLIC "+JSON.stringify(t.publicId)+" ") : "")+
(t.systemId? JSON.stringify(t.systemId) :"")+
">\n" + d.documentElement.outerHTML );
}
</script>
</head>
<body>
<textarea id="output"></textarea>
<iframe id="iframe-source" src="iframe.html" onload="test()"></iframe>
</body>
</html>
this also uses HTML.outerHTML to make sure you get any attribs on the documentElement.

Stylesheet ignored when using body onload and document.write

I am messing around with JavaScript experimenting to get a feel for it and have already hit a problem. Here is my html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="testing.js"></script>
</head>
<body onload="writeLine()">
</body>
</html>
Here is the JavaScript testing.js:
function writeLine()
{
document.write("Hello World!")
}
Here is the style sheet styles.css:
html, body {
background-color: red;
}
So a very simple example, but I may have chose an awkward example, using on-load in a body tag. So the code above loads and runs the function, but the style sheet does nothing, unless I remove the script tags in the head. I have tried putting the script tags everywhere else, but nothing works. I have researched on-line how to properly link to JavaScript files, and have no found no clear solution, can anyone point out my error?
I have used JavaScript before, but I want a clear understanding from the beginning before I use it any longer
You cannot use document.write after the document is closed (which it will be when onload fires) without destroying the existing document (including links to stylesheets).
Instead, use DOM manipulation, which is covered by chapters 8 and 9 of the W3C JavaScript Core Skills.
Your problem is with the document.write() called in a wrong moment*. This method prints given text at current place in the page as was intended to work while the page still loads. Because you are calling it when the whole page was loaded, the results are unexpected (undefined?)
Instead you should manipulate the dom tree directly:
function writeLine() {
var text = document.createTextNode("Hello World!");
document.body.appendChild(text);
}
Actually in Opera browser I see red background for few milliseconds and then it goes back to white. Try commenting out document.write() - the background is as expected. Moreover you should include <script> tag at the end of body, but this won't solve your problem.
* to be honest, there is no good moment for calling document.write(), avoid it
In your particular example it doesn't matter where the script tag is added as the document.write command executes after the content is rendered, overwriting the existing content.
If you add an alert before overwriting the content you can see your page is red before it gets overwritten with Hello World.

jQuery.html() removes scripts and styles

Is there a way to use jQuery.html() and not loose the scripts and styles? or any other non-jQuery way?
I'm trying to output the full HTML of the page the user is on. Is this even possible?
jQuery.html() removes scripts and styles
That isn't my experience (see below). In practice, you have to be aware that what you get back by querying the DOM for HTML strings is always going to be the interpreted HTML, not the original, and there will be quirks (for instance, on IE all the HTML tag names are IN UPPER CASE). This is because jQuery's html function relies on the browser's innerHTML property, which varies slightly browser to browser. But the demo below includes both style and script tags on Chrome 4, IE7, and Firefox 3.6; I haven't tried others, but I would expect them to be okay.
If you want to get the content of externally-linked pages as well as the inline content, you will naturally have to parse the result and follow the src (on scripts), href (on links that have rel = "stylesheet"), etc...
Demo:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
(function() {
$(document).ready(pageInit);
function pageInit() {
$('#btnGo').click(go);
}
function go() {
alert($('html').html());
}
})();
</script>
</head>
<body>
<input type='button' id='btnGo' value='Go'>
</body>
</html>
I see 2 scenarios here
you use jQuery.html(yourHTML) to overwrite the entire html of the page, so even the script tags were overwritten...
you use jQuery.html() to retrieve the entire document html. if this is the case you need tu ensure that the element on which .html() function is used, is the entire html... as T.J. Crowder suggested $('html').html()

Categories