问题
I'm currently working on a page where a user has the ability to edit some HTML. To enable him to do it in a nice way, I'm using TinyMCE, as it has a rather nice interface. The problem is that the underlying framework is ASP.NET MVC which doesn't allow for easy submission of HTML. As the HTML the user submits is passed on to another backend, I'd rather not just declare submission to be able to contain HTML. Instead I'd like to just run escape
or similar on the form fields before submission.
This approach works okay without TinyMCE but with TinyMCE it looks like it has a hook for onSubmit
. As I haven't found a way to either hook into that function for TinyMCE or prevent it from happening I'm somewhat stuck. What does work, is to remove the editor before submission but it's kind of clunky and rather noticeable.
So what would be the correct/best way to either hook into the onSubmit
event for TinyMCE or remove the hook from TinyMCE?
The below code provides a minimal working example. To see what I mean, run it and click "Show Value". You will see that the textarea
contents is unescaped. If you click "Escape" it will run escape
on the textarea
. You can check it with "Show Value". If you proceed to click "Submit" and check the value afterwards, you will find that it's not escaped anymore.
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script src='http://cloud.tinymce.com/stable/tinymce.min.js'></script>
<script>
tinymce.init({
selector: 'textarea',
setup: function(editor){
// Let the editor save every change to the textarea
editor.on('change', function(){
tinymce.triggerSave();
});
}
});
$(document).ready(function(){
$("form").submit(function(e){
// Do one final save
tinymce.triggerSave();
// Escape every textarea
$("textarea").each(function(k,v){
$(this).val(escape($(this).val()));
});
// Prevent submit for this example
return false;
});
$("#showvalue").click(function(){alert($("textarea").val())})
});
</script>
</head>
<body>
<form method="post" action="URL">
<textarea><html>Here is some code<strong>With some HTMl</strong></html></textarea>
<button>Submit</button>
<button type="button" onclick="document.querySelectorAll('textarea')[0].value = escape(document.querySelectorAll('textarea')[0].value)">Escape</button>
<button type="button" id="showvalue">Show Value</button>
</form>
</body>
</html>
回答1:
The actual solution seems to be rather easy. As you can see in the init for TinyMCE there is already an event for change
that an action is bound to. For now it seems to work to bind to the submit
event and just return false.
tinymce.init({
selector: 'textarea',
setup: function(editor){
// Let the editor save every change to the textarea
editor.on('change', function(){
tinymce.triggerSave();
});
// Do nothing when submitting the form
editor.on('submit', function(){
return false;
});
}
});
来源:https://stackoverflow.com/questions/42826979/remove-onsubmit-event-hook-from-tinymce