Home » Javascript » How to escape a hyperlink but not a script within a hyperlink

How to escape a hyperlink but not a script within a hyperlink

Posted by: admin June 30, 2018 Leave a comment

Questions:

I would want help in fixing the following issue :
As per my need , in my JSF textarea if i have a link, that should be clickable . To achieve this , i have the following code :

protected void getEndTextToRender(FacesContext context, UIComponent component,
        String currentValue) throws IOException
{
    String currTextValue = currentValue;
    if(currTextValue != null)
    {
        StringBuilder textValue = new StringBuilder(currTextValue.length());
        Pattern titleFinder = Pattern.compile("<a[^>]*>(.*?)</a>",
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
        Matcher regexMatcher = titleFinder.matcher(currTextValue);
        int startIndex = 0, loopStartIndex = 0, loopEndIndex = 0;
        while(regexMatcher.find())
        {
            loopStartIndex = regexMatcher.start();
            loopEndIndex = regexMatcher.end();
            textValue.append(
                    getEscapedString(currTextValue.substring(startIndex, loopStartIndex)));
            String tempLoopString = currTextValue.substring(loopStartIndex, loopEndIndex);
            if(tempLoopString.contains(CONTEXT_PATH))
            {
                tempLoopString = tempLoopString.replace(CONTEXT_PATH,
                        ServletUriComponentsBuilder.fromContextPath(
                                (HttpServletRequest)context.getExternalContext().getRequest())
                                .toUriString());
            }
            else
            {
                String newTrimmedStr = tempLoopString.replaceAll(" ", "");
                if(!StringUtils.containsIgnoreCase(newTrimmedStr, "target='_blank'")
                        && !StringUtils.containsIgnoreCase(newTrimmedStr, "target=\"_blank\""))
                {
                    tempLoopString = new StringBuilder(tempLoopString)
                            .insert(StringUtils.indexOf(tempLoopString, ">"),
                                    " " + TARGET_BLANK)
                            .toString();
                }
            }
            textValue.append(tempLoopString);
            startIndex = loopEndIndex;
        }
        textValue.append(getEscapedString(currTextValue.substring(startIndex)));
        currTextValue = textValue.toString();
        ((HyperLinkOutputText)component).setEscape(false);
    }
    super.getEndTextToRender(context, component, currTextValue);
}

As a result , if i pass <a href="url"><script>alert('hi')</script></a>
<a href="www.google.com">Google</a>
<script>alert('hi')</script>
my output would be a pop-up – hi and a link to google and text alert(‘hi’).
I do not want the script popup, but the link should be clickable.
Can somebody please help me with respect to this issue.
Thanks in advance.

Answers: