Autolinker.js icon indicating copy to clipboard operation
Autolinker.js copied to clipboard

Protocol allow/deny list

Open andyford opened this issue 4 years ago • 2 comments

Sorry this is not an issue but more of a feature request (or maybe I just didn't find it in the readme)

Is there a way to allow or deny specific protocols? In my case I really only want to link http and https protocol urls to get linked. (no ftp or any special application specific protocols)

Does this option already exist and I just missed it?

andyford avatar Aug 21 '20 21:08 andyford

Hey @andyford,

So there's no way to set a protocol allow or deny list at this time, but as a workaround for the moment, you could try this in the replaceFn. Something like this:

var linkedText = Autolinker.link(inputText, {
    replaceFn : function(match) {
        if (match.getType() === 'url') {
            if (!/https?:\/\//.test(match.getUrl()) {
                // url does not start with 'http://' or 'https://', do not autolink
                return false;
            }
        }
        return true;  // autolink everything else as usual
    }
});

Best, Greg

gregjacobs avatar Aug 22 '20 18:08 gregjacobs

Thanks @gregjacobs! That's exactly what I needed! I feel a little silly for missing replaceFn in the docs.

Quick note: if any one else needs this bit of code, there's a missing closing paren in the inner if statement it should be if (!/https?:\/\//.test(match.getUrl())) { (@gregjacobs - feel free to delete this note [if you can] and update your comment if you like)

I keep waffling between more verbose but easier to read code and Perl-esque one-liners. Here's a one-liner version of the workaround: replaceFn: (match) => !(match.getType() === 'url' && !/https?:\/\//.test(match.getUrl())),

andyford avatar Aug 22 '20 20:08 andyford