Spomky-Labs / pwa-bundle

PHP library for generating a full featured PWA manifest
https://pwa.spomky-labs.com
MIT License
28 stars 1 forks source link

Disable profiler when creating screenshots #147

Closed tacman closed 1 month ago

tacman commented 2 months ago

Description

I can't imagine that anyone would want to see the debug toolbar in the screenshots they're creating.

It can be disabled programmatically:

https://symfony.com/doc/current/profiler.html#enabling-the-profiler-programmatically-or-conditionally

Example

No response

Spomky commented 1 month ago

I think an event subscriber like as follows should do the job. Not tested, but basically it disables the profiler if avaialble and if the user agent contains a specific keyword

<?php

namespace App\EventSubscriber;

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Profiler\Profiler;

final readonly class MySubscriber implements EventSubscriberInterface
{

    public function __construct(
        #[Autowire(service: 'profiler')]
        private ?Profiler $profiler = null
    ){}

    public static function getSubscribedEvents(): array
    {
        return [
            'kernel.request' => 'onKernelRequest',
        ];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        if ($this->profiler === null) {
            return;
        }

        $userAgent = $event->getRequest()->headers->get('user-agent');
        if ($userAgent === null || !str_contains($userAgent, 'xxxxxxx')) { // <= PUT THE USER-AGENT KEYWORD HERE
            return;
        }

        $this->profiler->disable();
    }

}
tacman commented 1 month ago

Great idea. Then the pwa:create:screenshots will set a user-agent?

Spomky commented 1 month ago

It looks like it is possible. The user-agent is set to something something HeadelessChrome/something, which is already a clue.

See https://webscraping.ai/faq/symfony-panther/is-there-a-way-to-simulate-different-user-agents-with-symfony-panther

use Facebook\WebDriver\WebDriverCapabilityType;

$customUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) PWABundle/123.0.0.0 Safari/537.36';
$client = static::createPantherClient([
    'capabilities' => [
        WebDriverCapabilityType::CHROME => [
            'args' => ["--user-agent={$customUserAgent}"],
        ],
    ],
]);
github-actions[bot] commented 1 week ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.