Confluence Estimated time to read macro

Hi,

I have developed a macro which provides the estimated time to read along with the number of words in Confluence page.

The output of the macro need to look like this
“Estimate time to read: 2 min (WORDS 400)”
When I preview the page the output looks like
“Estimate time to read: (WORDS)”
After saving the page it shows
"“Estimate time to read: 2 min”

Anyone here provide work around for me, so that I can get the expected output.

Thanks.

Without knowing what you’re doing it’s kinda hard to say. My guess is that you’re either not accessing the right dom or being triggered at the right time.

So…

How are you triggering your javascript? How are you accessing the content to count the words?

Macro is not evaluated in the edit mode, thus you don’t see values. You should write a js and hook it while editing. Problem with that is that text is within an iframe so I’ve found this function

function countWords(s){
    s = s.replace(/\n/g,' ');
    s = s.replace(/(^\s*)|(\s*$)/gi,''); 
    s = s.replace(/[ ]{2,}/gi,' '); 
    return s.split(' ').length; 
}

for word count, this function

function putScriptInIframes(script, scriptId) {

   var $iframes = $('iframe');
   $iframes.each(function () {
        var thisDoc = this.contentWindow.document;
        if ( ! thisDoc.getElementById(scriptId)) {
            var scriptObj = thisDoc.createElement("script");
            scriptObj.type = "text/javascript";
            scriptObj.id = scriptId;
            scriptObj.innerHTML = script;
            thisDoc.body.appendChild(scriptObj);
        }
    });
}

for injecting javascript within iframe.

Now, use some js minifier to minify function 1 and lets call it f1. You can now write in the js console while editing:

putScriptInIframes("f1",1);
putScriptInIframes("countWords('hello there')",2);

this will run in the iframe. So, only trivial thing left is to swap the text of the editor with the “hello there”, which can be done by

var text=document.getElementById('tinymce').innerText;

and hook the countWords(text) now when #tinymce element changes.

1 Like