Background
When user adds a link to a paragraph block (or some other richtext block where links can be added) and sets the Open in new window flag, the block editor produces the following markup.
<p>
This is a text paragraph, which has <a href="#" target="_blank">an external link</a> in it.
</p>
To my understanding WCAG 2.0 criterion recommends adding a warning text to links that have the target="_blank"
attribute. So the end result should be something like this,
<p>
This is a text paragraph, which has <a href="#" target="_blank">an external link<span class="screen-reader-text show-on-hover">(opens in new window)</span></a> in it.
</p>
Possible solutions
I know that one can use blocks.getSaveElement
filter to modify the block save output, but I'm afraid that I might have to duplicate and re-implement a lot of code, as noted here, if I mess with the HTML output of the default blocks.
Then there's the wp.element.cloneElement
method, but I don't quite understand how can I detect all the a[target="_blank"]
elements with it and append the screen reader text spans to the found links.
Using render_block
or the_content
PHP filters, to detect the links and append HTML to them, seems a bit wasteful to me as the same processing would be done over and over again on every page load instead of adding the screen reader text just once for each link. The same goes with frontend js solutions.
I experimented with registerFormatType
to add a span tag to a selected link and it somewhat worked. I noticed that, if only the link element is selected, the span
would end up inside the a
tag - which is what I wanted.
But if there was even one empty space, before or after, selected along the link, then the whole a
tag would get wraped inside the span
- not ideal considering that the not-so-techinal content editor should be able to this without errors.
Question
How can I append a screen reader text span
to a link in block editor, when the "Open in new window" flag is activated?