Reputation: 3782
I am using tinymce editor to provide rich text formatting and along with that I want to provide the option of autosave. I managed to write a script that does exactly that, but there is one problem. I do not want to call that save function if the window is not the current tab, so that unnecessary save calls are not made.
To over come this I using the $(window).focus()
but this does not seem to work because when the tinyMCE editor is in focus (meaning I am typing in it) somehow the window goes out of focus (most probably because tinyMCE editor uses an iFrame) and as a result my periodic update function is not being called.
i would very easily solved this problem if there was a handler .onFocus
for the editor but there seems to be none. Can anybody suggest me how can I overcome this problem? My code is given below
/* Function to be called for saving the blog */
function saveBlog(){
var ed = tinymce.activeEditor;
/* Ajax call will be done only when some changes has been made in the editor*/
if (ed.isDirty())
{
ed.save();
var link = $(this).attr("href");
var cur_elem = $(this);
cur_elem.html('saving...');
cur_elem.addClass('unclickable');
$.ajax({
type: "POST",
url: link,
data: $("#blog_form :input[name!='csrfmiddlewaretoken']").serialize(),
dataType: 'json',
success: function(){
cur_elem.html('Save');
cur_elem.removeClass('unclickable');
}
});
}
};
var interval_id;
/* Timer resumes when the window comes back in focus */
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(saveBlog, 5000);
});
/* Whenever window goes out of focus the timer is cleared */
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
/* Starts the auto saving for the first time */
$(document).ready(function(){
interval_id = setInterval(saveBlog, 5000);
});
Can anybody help with this problem, I just need to know when the tinyMCE editor instance is in focus so that I can resume the auto saving periodic function. I can add that in addition to the $(window).focus
Upvotes: 3
Views: 4440
Reputation: 5692
Although this post is quite old, I have written a plugin that sends the form data to the specified url every x seconds. I have blogged it here.
In short, the idea is to create an iframe, change the target and action of the form dynamically, and submit the form to stimulate an ajax effect. Once saved, I am putting the form element into its initial state so that if the user wants to save manually he or she will not have any difficulties.
Please note that the plugin I've written is for tinymce4. You'll have to change the source code a bit for older versions.
Upvotes: 2