Get external links from Rich Text Editor

Sometimes you want to manipulate links generated by the content authors added in the Rich Text Editor. It could be by adding query strings, set the target attribute to _blank if the link is an external link etc.

Sitecore resolves the internal links in the Rich Text Editor by using the ExpandLinks processor in the renderField pipeline (located in the web.config file) converting the GUID into valid URLs, but letting the external links unhandled. So if you want to manipulate external links, you could do it by adding a new processor into the renderField pipeline.

In this example, I want to add target=”_blank” if the link is an external link.

The code:

using System.Text.RegularExpressions;
using Sitecore.Data.Fields;
using Sitecore.Pipelines.RenderField;
 
namespace MySitecoreExtensions.Pipelines.RenderField
{
    public class AddTargetAttributes
    {
        public void Process(RenderFieldArgs args)
        {
            if (args.FieldTypeKey == "rich text")
            {
                args.Result.FirstPart = SetTargetAttribute(args);
            }
        }
 
        private string SetTargetAttribute(RenderFieldArgs args)
        {
            string fieldValue = args.FieldValue;
            string regexURL = @"(<a.*?>.*?</a>)";
 
            Regex regex = new Regex(regexURL, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
            MatchCollection matches = regex.Matches(fieldValue);
 
            foreach (Match match in matches)
            {
                if (!match.Success)
                    continue;

                string regexHref = @"href=\""(.*?)\""";
                Match maHref = Regex.Match(match.Value, regexHref, RegexOptions.Singleline);
                if (!maHref.Success)
                    continue;
 
                if (maHref.Value.ToLower().Contains("http://"))
                {
                    string enrichedURL = match.Value.Insert(2, " target=\"_blank\" ");
                    fieldValue = fieldValue.Replace(match.Value, enrichedURL);
                }
            }
 
            return fieldValue;
        }
    }
}


Finally I add a new processor to the renderField pipeline (into an include file):

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
            <renderField>
                <processor type="MySitecoreExtensions.Pipelines.RenderField.AddTargetAttributes, MySitecoreExtensions" patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetInternalLinkFieldValue, Sitecore.Kernel']"/>
            </renderField>
    </sitecore>
</configuration>


No comments: