Get the count of words in TinyMCE with Word Count plugin

1k Views Asked by At

I wanna get the count of words in the textarea and make changes to my users account based on the number of words. For example: a person writes 1000 words and its credibility goes up in the account (I use Django)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>

    <script>
      tinymce.init({
        selector: "textarea",  // change this value according to your HTML
        plugins: "wordcount",
        toolbar: "wordcount"
      });

I Use this But I got an error : TypeError: tinymce.activeEditor is null

var wordcount = tinymce.activeEditor.plugins.wordcount;

console.log(wordcount.body.getWordCount());
console.log(wordcount.body.getCharacterCount());
console.log(wordcount.body.getCharacterCountWithoutSpaces());

console.log(wordcount.selection.getWordCount());
console.log(wordcount.selection.getCharacterCount());
console.log(wordcount.selection.getCharacterCountWithoutSpaces());

**

  </head>

  <body myFunction()>
    <form method="post">
      <textarea id="mytextarea"></textarea>
    </form>
  </body>
</html>

    enter code here
1

There are 1 best solutions below

0
Michael Fromin On

The API call tinymce.activeEditor only works when there is an "active" editor on the page. Depending on when you are running your code there may not be an "active" editor at that exact time.

When you first run tinymce.init({}) it takes TinyMCE some time to finish its initialization so until that happens there is no "active" editor. Without seeing running code it will be hard to tell you definitively why you are getting the error you reference but most often I see that when people try to interact with TinyMCE either...

  • before the editor has finished initializing
  • after the editor was removed from the page