Save full html page sourcecode in a Javascript variable - javascript

I search the best way to save a source code from a html page in a Javascript variable.
The html source code is loaded with php & mysql and looks like for example this:
<!DOCTYPE html>
<html>
<body>
<h2>HTML Images</h2>
<p>HTML images are defined with the img tag:</p>
<img src="w3schools.jpg" alt="W3" width="104" height="142">
</body>
</html>
If I try to simple save it to a variable
var html = "<?php echo $my_html; ?>";
I get different errors. For example Uncaught SyntaxError: Unexpected token '<'. I think the reason is that there are quotation marks, line breaks, special chars and so in the the content of $my_html. Of course I can save the html content before to an invisible textarea and take then the content of the textarea to the variable. But is there no other / better way?

You don't need to set the JavaScript variable independently. document.documentElement.outerHTML; is a reference to the HTML contents.
var markup = document.documentElement.outerHTML;
console.log(markup)
<!DOCTYPE html>
<html>
<body>
<h2>HTML Images</h2>
<p>HTML images are defined with the img tag:</p>
<img src="w3schools.jpg" alt="W3" width="104" height="142">
</body>
</html>

Since you are working with PHP, I would recommend using a native function prior to setting the JS variable.
Have you tried addslashes()?
<!DOCTYPE html>
<html>
<body>
<?php
$str = addslashes('What does "yolo" mean?');
echo($str);
?>
</body>
</html>

Related

how to isolate js script from the html code?

i'd like to isolate the javascript code from the html code in two diferent files, originally I had this code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
</body>
</html>
<script>
$(document).ready(function () {
$("#body").text("JS Text");
});
</script>
and the output of the <-p-> was the expected "JS Text".
Then I tried to isolate the js script to another file (script.js):
window.onload = function(){
var text = document.getElementById('body');
text.innerHTML ='JS Text';
}
I've also make the reference at the html file:
<script type="text/javascript"src="scripts.js"></script>
but then the output text is no longer the expected (JS Text) but (HTML text)
what else do I need to make the js script work again?
First, it is invalid to place anything after the closing HTML tag, so while your first bit of code worked, it was invalid.
If you remove the JavaScript and place it in its own file, it will continue to work as long as you reference the file properly (use a relative reference and test the file on a web server) and place the script element just prior to the closing body tag so that when the script is processed and attempts to find the right DOM element, the DOM will have been loaded at that time.
FYI:
If you have JQuery in the referenced script file, then your
script that references JQuery will need to occur in the HTML prior
to the script that uses it.
The type attribute in the script tag has not been needed in
several years.
It's not a good idea to name anything body so that you won't cause
confusion with the body element.
Don't use .innerHTML when the string you are working with doesn't
contain any HTML. .innerHTML has security and performance
implications. Use .textContent instead.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
<script src="relativePathToFile.js"></script>
</body>
</html>

Navigation bar in html5

I have a quick question. I'm wondering if it is possible to have a external html file with my navigation bar in it and have that be put in to all of my pages for my website. If so how do I do this? I have tried using these methods:
<script rel="import" src="navigation-bar.html"></script>
$("#nav-bar").load("navigation-bar.html")
but so far neither of them have worked... Do I have to use PHP and if I do how do I implement this.
please help.
I would use PHP to do this.
Here is the structure of how it would work.
<html>
<head>
<?php require('/directory/to/your/header.php'); ?>
</head>
<body>
...Your Content Here
</body>
</html>
In a separate header.php file you would include your navbar.
Header.php
<?php
echo '...enter your Navbar HTML code';
?>
Your file will have to have the extension .php and every time you write in php, you must start and end with
<?php
...enter your php code...
?>
You can mix php with html simply by writing the php into the HTML. Take for example the following href:
Your link Name
For more information please refer to :
http://php.net/manual/en/
put:
include("navigation-bar.html")
on top of your code.
This way you won't have to write the same navigation code in each webpage that you are going to host.
OR
you can try
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
Read more at: http://www.w3schools.com/howto/howto_html_include.asp
This is probably the simplest solution that should work even in user agents without scripting support.
For example, your page will look like this:
<html>
<body>
<iframe src="navbar.html" class="navbar" />
</body>
</html>

How can I display HTML tags as Text using jQuery?

I am trying to display unrendered HTML code using class html and the below jquery code.
Its working for every tag except for tags <html>, <head> and <body>.
Is there a way these can also be displayed as text?
$(document).ready(function () {
$('.html').each(function () {
$(this).text($(this).html());
});
});
HTML code:
<pre>
<div class="html">
<html>
<head><title>Title</title></head>
<body>
<p>Unrendred html</p>
</body>
</html>
</div>
</pre>
Expected content:
<div class="html">
<html>
<head><title>Title</title></head>
<body>
<p>Unrendred html</p>
</body>
</html>
</div>
Actual content:
<title>Title</title>
<p>Unrendred html</p>
Your HTML is invalid. You can't have most of those tags where you are putting them.
When the browser tries to parse your invalid HTML, it hits your errors and attempts to recover from them.
The result of this is that they are never put inside the .html element in the DOM, so when you try to convert the DOM back to HTML they won't appear.
The only way you could scrape them out of there would be to refetch the raw source code from the server and then parse the HTML yourself.
Just write the HTML correctly in the first place. If you want to render a < character then put < in the HTML (and so on). Don't try to escape the HTML with JavaScript after the browser has already parsed it.
you need to replace the tag syntax as below
expected result at this fiddle example - http://jsfiddle.net/uEMh2/
<pre>
<div class="html">
<html>
<head><title>Title</title></head>
<body>
<p>Unrendred html</p>
</body>
</html>
</div>
</pre>
escapeHTML {
return html.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Thats the way prototype handles it.
i tried to solve your problem by jquery but you have to add one unused <pre> tag to your code and two lines of jquery code
if you ignore <pre> and jquery script on output then everything is as you wan't
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var data = $('html').html();
data = "<!doctype html>\n<html lang=\"en\">\n"+data+"\n</html>";
var data = $('pre#html-code').text(data);
});
</script>
</head>
<body>
<pre id="html-code"></pre>
</body>
</html>
escape the <> characters - on your html, and on your js as well use html function instead of html()
<pre>
<div class="html">
<p>< html / ></p &gt
<head ><title >Title</title></head >
<body >
<p >Unrendred html</p >
</body >
</html>
</div>
</pre>
$(document).ready(function () {
$('.html').each(function () {
$(this).text($(this).html);
});
});
http://fiddle.jshell.net/p3BXK/16/

highlightjs with html code

How do I put my HTML code so that highlight.js prettify it ?
I tried
<pre>
<code>
<!-- HTML Prettify -->
<div>
<pre class="pre-code-ception"><code> haha </code></pre>
</div>
</code>
</pre>
I did put at the end of my file :
<script type="text/javascript">
hljs.initHighlightingOnLoad();
</script>
But everything is shown as plain HTML.
Oh, I think I understand the problem. You need to escape the HTML within the <code> element, otherwise it will be interpreted as HTML instead of text (you want the HTML displayed literally, not interpreted as part of the webpage structure).
Change every < to < and > to >, as well as any other special HTML characters in your code sample. (If you're generating the page on the fly, most languages have a utility function to escape the HTML for you.)
user2932428 solution without jQuery:
document.querySelectorAll("code").forEach(function(element) {
element.innerHTML = element.innerHTML.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
});
To add to #Cameron's answer on escaping your html:
If you have a large amount of code that you want to highlight and don't want to resort manually escaping everything, one option is to save it as a variable using heredoc syntax and use a variant of htmlspecialchars() (PHP) to escape it. Heredoc lets you save a multi-line string as a variable without having to use concatenation operators.
Then it's just a matter of echoing it within your <pre><code>...</code></pre> block.
The benefit of using this method is the code remains readable in your document.
Example:
<?php
$code = <<< EOT
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img src="image.png" />
</body>
</html>
EOT;
?>
<pre>
<code class="html">
<?php echo htmlspecialchars( $code ); ?>
</code>
</pre>
One thing to note about using heredoc is that your closing EOT must be completely left-aligned.
you have to escape the content in <code class="html">
$('code').each(function() {
var that = $(this);
// cache the content of 'code'
var html = that.html().trim();
that.empty();
// escape the content
that.text(html);
});
hljs.initHighlightingOnLoad();

Simple jQuery .load Example Not Working

I'm sure this is a fairly basic question, but I'm relatively new to jQuery so was hoping someone might be able to help.
Basically, I need to load an HTML snippet into a page. This works fine when the snippet contains just HTML, but not when it contains a script.
I've stripped down my code to the bare minimum for clarity. This is index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<h1>Heading</h1>
<div id="banner"></div>
<script>
$(document).ready(function(){
$('#banner').load('banner.html');
});
</script>
</body>
</html>
And banner.html contains just the following (as an example):
<h2>Subheading</h2>
<script>
document.write('Hello');
</script>
The script is executed, but for some reason it strips out the rest of the HTML in both index.html and banner.html (i.e. it just displays "Hello" and nothing else).
Any help greatly appreciated!
document.write after the page has load writes to the document, and at the same overwrites everything else currently in the document, that's why you end up with only the string "hello".
Just remove the document write :
<h2>Subheading</h2>
<p id="test"></p>
<script>
document.getElementById('test').innerHTML = 'hello';
</script>
that is becuase when banner.html is loaded .. the script inside banner.html get executed, which writes "hello" in your document(the document here is your entire index.html)
one way to understand this is by replacing certain content of banner.html rather than the whole document.
banner.html
<h2>Subheading</h2>
<div id="divID"></div>
<script>
$('#divID').html('hello'); //using jquery .. gets the element with id as divID and replace the HTML
</script>
here i am replacing just the div whose id is "divID" rather than replacing the enrite document

Categories

Resources