How to extract HTML content from TinyMCE Editor - javascript

I'm a beginner on Javascript/TinyMCE and I try to understand how is it possible to get the HTML content from the editor, and show it with a simple alert() function.
I've this minimalist config on my HTML page :
<div id="tiny">
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "specific_textareas",
editor_selector : "mceEditor"
});
</script>
</div>
<form method="post" action="somepage">
<textarea id="myarea1" class="mceEditor">This will be an editor.</textarea>
</form>
On the TinyMCE Website, They explained that i have to use this :
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
And here too
tinymce.activeEditor.getContent()
I don't know why it doesn't work
Someone have an idea ?

I don't know why it doesn't work
It's not working because
console.debug(tinyMCE.activeEditor.getContent());
tinymce.activeEditor.getContent();
these statements are not being executed.
Try to follow this FIDDLE ....
tinyMCE.init({
// General options
mode : "specific_textareas",
editor_selector : "mceEditor"
});
Function for getting content ....
function get_editor_content() {
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
//method1 getting the content of the active editor
alert(tinyMCE.activeEditor.getContent());
//method2 getting the content by id of a particular textarea
alert(tinyMCE.get('myarea1').getContent());
}
Get the content of editor on button click ...
<button onclick="get_editor_content()">Get content</button>

Maybe it's the case? Your variable is tinyMCE, but you are calling getContent() on tinymce. JS is case sensitive ;)

I was looking for a solution and tried some of the above then went looking more on the tinymce documentation and found this to be effective.
Using the tiny mce 4
function getHTML()
{
tinymce.activeEditor.on('GetContent', function(e) {
console.log(e.content);
});
}
just call that function with an onclick and see what the results are...
My source is:
http://www.tinymce.com/wiki.php/api4:class.tinymce.ContentEvent

TinyMCE creates an iframe under the format '#textareaid'+'_ifr' So by using jquery we can query the HTML contents of the text area you like
the iframe id will be your textarea Id with "_ifr" appended to that. So you can extract HTML contents from tinyMce
$('#textareaId_ifr').contents().find("html").html();

Related

Unable to change the link of a button using Javascript

Hello I am a total newbie (I don't code) and I made a wordpress website in two different languages (french and english) using the Polylang plugin.
But I am facing the following problem : in my website, there is a button linking to a Facebook page in english and when the website is switched to french, I would like the button to link to another Facebook page (that will be in french).
From what I searched so far, I understand that this would be possible using javascript.
And I tried many variations of the following code with no result :
<script>
jQuery(document).ready(function(){
$('html[lang=|fr] .fa-facebook').attr('href', 'https://myfacebookpage.com');
});
</script>
"fa-facebook" is the css class of the social media button.
What am I doing wrong and how can I fix that please ?
Thank you !
Edit : here is the html code of the french version : jsfiddle.net/yup5zxng
I also tried with not result :
<script>
jQuery(document).ready(function(){
$('html:lang(fr-FR) .fa-facebook').attr('href', 'https://myfacebookpage.com'); }); </script>
Basically what you should do is check the language of the <html> tag on document ready and after loop through all the facebook links and update their href. Something like this:
$(document).ready(function() {
const documentLanguage = $("html").attr("lang");
const facebookLinks = $(".fa-facebook");
facebookLinks.each(function(index, link) {
if (documentLanguage === "fr-FR") {
$(link).parent().attr("href", "https://facebook.com/my-french-site/");
} else if (documentLanguage === "en-EN") {
$(link).parent().attr("href", "https://facebook.com/my-english-site/");
}
});
});
Here is a live sample: https://jsfiddle.net/rhernando/kwndv609/3
EDIT
I forgot about the tree structure of your DOM the class element is an <i> tag so you have to point to it's parent element. The updated code should work.
you have a typo in the attribute selector:
| should be before =, not after:
$('html[lang|=fr] .fa-facebook')
More about attribute selectors here: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Load data into TinyMCE programmatically

I have multiple text-areas that I'd like to enhance using tinyMCE. I can get the text areas to show as the Rich Text Editors by initializing TinyMCE on all text areas in the page as below:
$(function () {
tinymce.init({
selector: "textarea",
statusbar: false,
setup: function (editor) {
editor.on('change', function () {
editor.save();
});
}
});
});
This also handles the sync process between the Tiny editor and the actual textarea.
My html, that populates the text areas looks like this:
<div id="divEditor1" class="container-fieldset">
<div class="editor-label-field" style="left: 50px">
<%:Html.LabelFor(Function(model) model.divEditor1, "divEditor1")%>
</div>
<div class="editor-field-fn">
<%:Html.TextBoxFor(Function(model) model.divEditor1, New With { Key .class = "ucase-input" } )%>
<%:Html.ValidationMessageFor(Function(model) model.divEditor1)%>
</div>
</div>
<div id="divEditor2" class="container-fieldset">
<div class="editor-label-field" style="left: 50px">
<%:Html.LabelFor(Function(model) model.divEditor2, "divEditor2")%>
</div>
<div class="editor-field-fn">
<%:Html.TextBoxFor(Function(model) model.divEditor2, New With { Key .class = "ucase-input" } )%>
<%:Html.ValidationMessageFor(Function(model) model.divEditor2)%>
</div>
</div>
... etc
I can read the content from the TinyMCE editors like this:
for (var i = 0; i < numberOfEditors; i++) {
sFieldValue = document.getElementById("FormFieldText" + i).value;
//sFieldValue = tinyMCE.get("FormFieldText" + i).getContent(); -> or like this, works just as well.
};
The problem I am having is getting the TinyMCE editor box to display the already existing text on page load (text read from a database), since it always shows up as an empty text box. However, the text is imported correctly in the original textarea in the background. Formatted and escaped, since it goes through some ajax calls.
I've seen I can set the content of tiny like this:
tinyMCE.get('my_editor').setContent(data);
However, I need to do it programmatically, in a way that all textareas on my page export the information to tiny. Just like the above
setup: function (editor) {
editor.on('change', function () {
editor.save();
});
}
Also, what would be the right time to un-encode the text so tiny can read it? (I assume this step is necessary)
If you initialize TinyMCE on each textarea before each textarea has its content then TinyMCE won't auto-magically go back and update itself when the textarea gets updated with content - it just does not work that way.
You could use TinyMCE APIs (as you already know from your post) to update the editor's content once you get the data. Alternatively you could delay initializing TinyMCE until after the data is fetched into each textarea.
Neither approach is better/worse - there are certainly multiple ways to solve this and they all work if implemented appropriately.
I ended up parsing the list of active tinymce instances by ID and populating each one with the corresponding text from the textareas in the background.
I came across this post looking for a solution to get the data from the database back into tinymce, and I ended up with
<textarea id="textarea"><?= htmlspecialchars($description); ?></textarea>
Just using php and the variable from the array from the database.

How change the CKEditor text using jQuery?

I have a textarea with CKEditor (bbCode Plugin).
<textarea id="editor1" name="conteudo" class="form-control" rows="3" required></textarea>
This is my CKEditor instance:
$( document ).ready( function() {
$( 'textarea#editor1' ).ckeditor();
} );
I'm making a JSON request that takes a value and I want this value to be modified in this textarea, I tried with jQuery but not worked !
Below is my attempt:
video_id = "lLi1Lx2xTKI";
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
description = data.data.description;
// Attempt here
$("#editor1").html(description);
});
UPDATE
I tried using '.val()' and not worked!
You can't simply add text to the CKEDITOR via jQuery, instead go with api given by CKEDITOR
CKEDITOR.instances.editor1.setData(data.data.description);
Here your code looks like
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
CKEDITOR.instances.editor1.setData(data.data.description);
});
Fiddle
Instead of writing the description directly into the text area, try the CKEditor setData method. You can find a description of it here:
http://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-popup
also be sure that your description variable does have a value, I'd use a temporary alert(description); for this but you may be able to do it with a javascript debugger also.

How to dynamically replace content in TinyMCE?

I want to replace all {baseurl} keywords to proper url in TinyMCE editor. How can i do that?
For example if user will add HTML in editor <img src="{baseurl}/image.jpg" /> i want to see this image in TinyMCE editor - so this will be replaced to <img src="http://mydomain.com
/image.jpg" />
Any ideas?
Here is the code that will replace your editor content. But you will need to do this action at the correct time.
var editor = tinymce.get('my_editor_id'); // use your own editor id here - equals the id of your textarea
var content = editor.getContent();
content = content.replace(/{\$baseurl}/g, 'http://mydomain.com');
editor.setContent(content);
With this solution I was able to modify the content on-the-fly, without replacing the content as whole:
tinymce.init({
setup: (editor)=>{
editor.on('init', ()=>{
$(editor.contentDocument).find('a').prop('title', 'my new title');
});
}
});
Maybe it helps someone :)
I used a very simple code working good with me
tinymce.get("page-content").setContent(''); // 'page-content' as the textarea id
tinymce.get("page-content").execCommand('mceInsertContent', !1, 'New content data');

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