3

If someone copies HTML from another site (like a title) and pastes it into a single-line text field, is there any way to automatically strip the HTML out? I know with rich text fields there are paste options to do this if you want, but with single-line text it sometimes throws one of those "an error occurred" messages in experience editor (logs come back with "After parsing a value an unexpected character was encountered: O") and sometimes it just shows the raw HTML instead. Thanks.

5
  • Not prepared to use this as an answer just yet, but you could use the item:saving event to wire up logic that would strip out HTML out of a field upon saving. Oct 26 '16 at 17:05
  • Only catch to that is sometimes the process is creating that "error occurred" on save, so it'd never hit item:saving. If it got past that it could work, but this seems more like something someone should really just paste it into a text editor first. Or just make the fields rich text and they deal with the consequences. :) Oct 26 '16 at 17:11
  • Yeah, my feeling is that you would either paste to notepad first or strip on save/saving. Oct 26 '16 at 18:11
  • 2
    some js to listen on single line text change? Oct 27 '16 at 0:18
  • Or more specifically - onpaste. Some info from w3s - w3schools.com/jsref/event_onpaste.asp Oct 27 '16 at 15:58
4

It looks like you want to directly paste the copied contents in experience editor, unlike RichText Field which provides dialog-popup.

In your layout, any master rendering page, or any global javascript, try to add this javascript.

<script>
    document.addEventListener('paste', function (e) {
        var content = e.clipboardData.getData('text/plain');
        document.execCommand('insertText', false, content);
        e.preventDefault();
        return false;
    });
</script>

Refresh the page with disabled cache status in browser and test

2
  • I have yet to try this answer for myself, but this is a unique solution that I've not seen yet. Nice answer. Oct 28 '16 at 4:13
  • I have tested this method in 8.2 and it seems very promising. It does not strip line-breaks, it will add <br/> appropriately. All other inline scripts are removed properly.
    – jrap
    Jul 14 '17 at 15:12
1

Have you considered hooking into item:saving Sitecore event? You can retrieve an item being saved and sanitize its fields:

public void OnItemSaving(object sender, System.EventArgs args)
{
    Item item = Event.ExtractParameter(args, 0) as Item;
    Error.AssertNotNull(item, "No item in parameters");
    //modify item fields as required
}

More info in John West's post: https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/repost-intercepting-item-updates-with-sitecore

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.