根据 URL/目标自动生成链接标题以实现可访问性

问题描述 投票:0回答:1

我想自动添加相应的附加内容:使用

target="_blank"
在外部 URL 上“打开外部链接”或“打开电子邮件程序”到文本中存在的电子邮件链接,例如作为链接标题。我认为这在以前的 TYPO3 中就已经存在了。我认为这对可访问性有利,对吧?有人可以帮我吗?

typo3 accessibility typo3-11.x
1个回答
0
投票

您可以实现 PSR-15 中间件来实现您想要的。

为此,请在以下位置注册中间件:
你的分机/配置/RequestMiddlewares.php
像这样:

<?php
return [
    'frontend' => [
        'vendor/your-ext/link-manipulator' => [
            'target' => \VENDOR\YourExt\Middleware\LinkManipulator::class,
            'after' => [
                'typo3/cms-frontend/site',
            ],
            'before' => [
                'typo3/cms-frontend/page-resolver',
            ],
        ],
    ],
];

然后实现中间件:
你的分机/类/中间件/LinkManipulator.php
像这样:

<?php
namespace VENDOR\YourExt\Middleware;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Http\ResponseFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;

class LinkManipulator implements MiddlewareInterface
{
    private ResponseFactory $responseFactory;

    public function __construct() {
        $this->responseFactory = GeneralUtility::makeInstance(ResponseFactory::class);
    }

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {

        $response = $handler->handle($request);
        $body = $response->getBody();

        $dom = new \DOMDocument();
        $dom->loadHTML($body);
        $xpath = new \DOMXPath($dom);
        $links = $xpath->query("//a[@target='_blank']");
        foreach($links as $link) {
            $title = $link->getAttribute('title');
            if($title != "") $title .= " ";
            $title .= "(opens external link)";
            $link->setAttribute('title', $title);
        }
        $links = $xpath->query("//a[starts-with(@href,'mailto')]");
        foreach($links as $link) {
            $title = $link->getAttribute('title');
            if($title != "") $title .= " ";
            $title .= "(opens email program)";
            $link->setAttribute('title', $title);
        }

        $html = $dom->saveHTML();
        $newResponse = $this->responseFactory->createResponse();
        $newResponse->getBody()->write($html);

        return $newResponse;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.