How to get source code of html page - javascript

This is a link for an example of Edit source Code:
http://neokoenig.github.io/jQuery-gridmanager/demo/tinymce.html
the button which value is </>.
He get the code HTML even if he changes the content of the grid.
How to get the source code HTML using JavaScript or jQuery?
Thanks.

Using JavaScript
document.documentElement.outerHTML
More info
or
document.documentElement.innerHTML
More info

you can use the html method with jquery, i.e for get the whole page html like this:
$( document ).ready(function() {
console.log($("html").html());
})

I'm not sure what you want to do exactly but if you want to get raw source code from jQuery you can use the following:
var html = $('element').html();
And with pure javascript from an id
var html = document.getElementById('id').innerHTML;
or from classname
var html = document.getElementsByClassName('class').innerHTML;
And to get the content of your example (which is an editor called tinymce) you can use the command tinymce.activeEditor.getContent(); or tinyMCE.get('myTextarea').getContent()
EDIT:
If you want to listen for changes with jQuery and display to html dynamically you'd want to do something like this:
$('yourTextArea').keyup(function() {
var html = $(this).val();
$('yourElementToDisplayTheHTML').html(html);
});

I've built a simple API, just use this:
<script src="https://cdn.jsdelivr.net/gh/Parking-Master/viewsource#latest/vs.js"></script>
In your JavaScript:
getSource('https://example.com/');

in http response header, you can find "content-type" header. that header indicates how contents of page should be rendered. so, if you want to render page as plain text("source code", as you mentioned), just change that header like this -> "content-type : text/plain; charset=UTF-8"
if you can use ajax in jquery or javascript
use like this
$("button").click(function(){
$.ajax({url: "page_you_want.html", success: function(result){
alert(result);
}});
});

Related

Get only a paragraph from http response [duplicate]

I'm looking for a way to get a HTML element from a string that contains HTML. Is it possible to use a jQuery selector to do this?
I have a Javascript function that gets an entire page from the server, but I only need one element from that page.
Yes, you can turn the string into elements, and select elements from it. Example:
var elements = $(theHtmlString);
var found = $('.FindMe', elements);
Just wrap the html text in the $ function. Like
$("<div>I want this element</div>")
If you are loading a page dynamically from a server then you can target just one element from the loaded page using the following form with .load()
$(selectorWhereToShowNewData).load('pagePath selectorForElementFromNewData');
For example:
$('#result').load('ajax/test.html #container');
Where:
#result is where the loaded page part will be displayed on the current page
ajax/test.html is the URL to which the server request is sent
#container is the element on the response page you want to display. Only that will be loaded into the element #result. The rest of the response page will not be displayed.
Just use $.filter
var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")
You can use $.find
$(document).ready(function() {
var htmlVal = "<div><span class='im-here'>Span Value</span></div>";
var spanElement = $(htmlVal).find("span");
var spanVal = spanElement.text();
alert(spanVal);
});

Load html file - and access element ID's

I have loaded a html file and "placed" it inside a div:
document.getElementById('my_div').innerHTML='<object type="text/html" data="table.html" ></object>';
Works fine, but when I try to get an element by it's ID in the table (from table.html) I get null/undefined.
var table = document.getElementById('my_table'); /* Nope! */
I guess I am doing it at the wrong time or place somehow. Can you help me please?
Best Regards
I would do this with jQuery's built-in AJAX method, .load(). Like so:
$(document).ready(function(){
$('#my_div_id').load('/filepath/table.html');
var table = $('#my_table');
// Other code, presumably :)
});

Getting element by tag name after getting a page using jQuery $.get

I am requesting a full page using $.get in jQuery and would like to get the content of a specific element. Separately, here is how things look:
$.get( "/page.html").done(function( data ) {
// get textArea.
});
and I want to get:
document.getElementByTagName("textArea")[0].value;
but I can't do getElementByTagName on data so what is the best way to do this?
I tried using find but that did not work so I ended up using filter and that returned the value of textArea that I needed:
$.get( "/page.html").done(function( data ) {
var textArea = $(data).filter("textarea")[0].innerText;
});
It's slightly different of what you are doing but i think it can help. You can call .load instead of get and add the whole page to a div say <div id="mydiv"></div>
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()})
however if you do not want mydiv to show you can hide at the beginning once the main page gets loaded and if you also don't want this div on your page you can remove it after the above task is performed.
$(document).ready(function(){
$('#mydiv').hide();
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()});
$('#mydiv').remove();
})
//str represents page.html
var str = 'gibberish gibberish <textarea class="test">hello world</textarea>gibberish';
$.each( $.parseHTML(str), function( i, el ) {
if(el.firstChild) console.log(el.firstChild);
});
Fiddle: http://jsfiddle.net/ez666/7DKDk/
You could try jquery load() function.
It will load from remote server and insert document into selected element.
It also allow us to specify a portion of remote document to be inserted.
Assume your remote textarea's id is "remote" and you want to fetch the remote content into a textarea which id is "local"
var result="";
$("#local").load("/page.html #remote", function(response, status, xhr){
result=$(this).find("#remote").val();
});
I'm not sure if you want to get the remote textarea and insert into the element of the current document.
If you just want to get the value of the remote textarea, you could just hide the load function invoking element
Hope this is helpful for you.
Since you're using jQuery anyway… have you tried $(data).find('textarea').first().val() yet?
This is assuming that data is a fragment. If it is not you will want to wrap it in a div or something first.

Finding and Executing / Extracting embedded JavaScript from AJAX result using jQuery

I'm performing an AJAX request to get a generated html page. I want to find a specific div in the result and inject it into the page where the request came from. I also want to include embedded script or script links which may be inside this div. Here is a simple sample of the page I want to get with AJAX
<html>
<head>
<script>alert("don't want this")</script>
</head>
<body>
<div id='findMe'>
<p>Some content</p>
<script>alert("want only this")</script>
</div>
<script>alert("don't want this")</script>
</body>
</html>
So I only want to extract the div with ID findMe. Here's what I have in the page that's doing the request
<script>
$(document).ready(function(){
$.ajax({
url: "ajax.htm",
success: function(data){
$(data).filter("#findMe").appendTo("#output");
},
dataType: "html"
});
});
</script>
<div id='output'></div>
But the script tag is missing and no alert appears. It seems to get taken out of the div. If I do
console.log($(data))
I can see each of the script tags as a document fragement, but how to I know which one was in the div before it was popped out?
You can try:
$(data).find('#findMe').appendTo('#output');
OR
$('<div/>').append(data).filter("#findMe").appendTo("#output");
Append data to a demo div (not exists in DOM) and make filter over that.
I think instead of .filter(), which filters the current jQuery collection, you have to use .find():
$(data).find("#findMe").appendTo("#output");
But I am unsure whether the script tag will be executed or not..
I had to treat the result as XML. Find the element I'm looking for in the XML object using jQuery .find(), select the actual node (array pos 0), convert the contents of the node to a string, and inject into the output div. This is the only method I've found that executes scripts only contained in the target div.
$.ajax({
url: "ajax.htm",
success: function (data){
var node = $(data).find("#findMe")[0];
if(node.xml)
{
$("#output").html(node.xml)
}
else if(new XMLSerializer())
{
$("#output").html((new XMLSerializer()).serializeToString(node));
}
},
dataType: "xml"
});

Get formatted HTML from CKEditor

I'm using CKEditor in my web app, and I'm at a loss as to how to get the contents of the editor with HTML formatting.
var objEditor = CKEDITOR.instances["sectionTextArea"];
var q = objEditor.getData();
This will get me the text entered in CKEditor, without any markup.
However,
var q = objEditor.getHTML();
will return a null value. What am I doing wrong?
getHTML isn't a method of a CKEditor object, so instead of null you should have a javascript error.
The method defined by the api is getData() if that doesn't work then you have some other problem in your code, try to use an alert to verify the contents at that moment.
just to know that the right method for this is getData() didn't help me. I did not know how to use it on the CKEditor object. and CKEDITOR.getData() doesn't work.
this is how getData() is used on the CKEDITOR object:
CKEDITOR.instances.my_editor.getData()
...where my_editor is the id of your textarea used for CKEditor.
The opposite of it is setData():
CKEDITOR.instances.my_editor.setData("<p>My Text</p>");
To get htmlData from editor you should use the code snippet bellow:
var htmldata = CKEDITOR.instances.Editor.document.getBody().getHtml();
If this solution won't work, check if you have BBCode plugins uninstalled.
Please update ckeditor config.js with the following line
config.fullPage = true;
This will return the full html when you request getData();
This worked for me:
CKEDITOR.instances["id"].getData()
I am using the preview plugin to get the full HTML content, hope it helps.
CKEDITOR.getFullHTMLContent = function(editor){
var cnt = "";
editor.once('contentPreview', function(e){
cnt = e.data.dataValue;
return false;
});
editor.execCommand('preview');
return cnt;
}
in ckeditor 5, you can get the html data with editor.getData()
here is an example:
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
console.log(editor.getData());
} )
.catch( error => {
console.error( error );
} );
For Java Users...
After pressing the submit button, the request goes by HTTP Post method. This Post request also contains the formatted html in the parameter named using the name attribute of the textarea.
So, if your textarea is something like...
<form method="post" action="createPDF.do"> <textarea name="editor1" id="editor1"/>
<input type="submit"/> </form>
Then, after pressing the submit button, you can get the formatted html in your servlet/controller by :
String htmlContent = request.getParameter("editor1");
You can also pass this variable containing the formatted html ('htmlContent') to ITEXT (or some other pdf converters) to create the pdf...
I realize this is old, but I had trouble finding an answer that made sense and returned the actual HTML, including images. If your ckeditor instance is attached to a textarea, you can simple get the value of the textarea to get the HTML.
For instance, if you're using jQuery:
$('#my_editor').val()
No need to go digging through the API.
If you have two CKEditor, you can use code bellow:
HTML
<textarea name="editor1"></textarea>
<textarea name="editor2"></textarea>
JS
CKEDITOR.replace( 'editor1' );
CKEDITOR.replace( 'editor2' );
var objEditor1 = CKEDITOR.instances["editor1"];
alert(objEditor1.getData()); // get html data
var objEditor2 = CKEDITOR.instances["editor2"];
alert(objEditor2.getData()); // get html data
Online Demo (jsfiddle)
I used the insert media feature in editor and .getData() did not return the required HTML to show the video thumbnail icon. The following worked for me to get the final HTML:
$(".ck-content").html()
Try this:
CKEDITOR.instances.YOUREDITOR.element.getHtml();
with CKEDITOR.instances.YOUREDITOR.element you select a DOM element and if you use
CKEDITOR.instances.YOUREDITOR.element.getHtml();
you can get all html from editor element.

Categories