NarūnasK
NarūnasK

Reputation: 4950

How to force external URLs inserted in the wagtail Draftail editor to open on the new tab?

Basically I need that the target="_blank" attribute would be added to all the external URLs inserted in the wagtail Draftail richtext editor:

external url

In [2]: wagtail.__version__
Out[2]: '2.0.1'

EDIT-1: This is not a duplicate. wagtail version 2 uses completely different richtext editor.

The proposed answer suggests $('a[href^="http://"]').attr('target', '_blank') which would add the appropriate attribute to the all links on the page which contain http://. It's very suboptimal solution, as there may be many more links on the page which do not require such a treatment. Obviously there must be more adequate fix, especially because wagtail already differentiate Internal and External links on the editor UI (see attached image).

EDIT-2:

It seems that in the wagtail.core.rich_text.feature_registry.FeatureRegistry class there is a method, which to my best understanding assign different handler to the different URL type, however I don't see what these these handlers are, how they get called or how to modify them?

def register_link_type(self, link_type, handler):
    self.link_types[link_type] = handler

Upvotes: 1

Views: 1445

Answers (1)

Eugene Zalivadnyi
Eugene Zalivadnyi

Reputation: 471

Create file wagtail_hooks.py and add the following lines:

class NewWindowExternalLinkHandler(LinkHandler):
    identifier = 'external'

    @classmethod
    def expand_db_attributes(cls, attrs):
        href = attrs["href"]
        return '<a href="%s" target="_blank" rel="noopener noreferrer">' % escape(href)

@hooks.register('register_rich_text_features')
def register_rich_text_handlers(features):
    features.register_link_type(NewWindowExternalLinkHandler)

Upvotes: 3

Related Questions