Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Access page opened in new window #671

Open
cosinus90 opened this issue Dec 14, 2024 · 0 comments
Open

Access page opened in new window #671

cosinus90 opened this issue Dec 14, 2024 · 0 comments

Comments

@cosinus90
Copy link

Hello,

There's a page where I click on an element and Javascript opens new page in new window. How to access it?
With the help of ChatGPT I have this code

    function openChart() {
        try {
            $session = $this->page->getSession();
            $discoverTargetsMessage = new Message('Target.setDiscoverTargets', ['discover' => true]);
            $session->sendMessage($discoverTargetsMessage);

            $this->js('document.querySelector("a[class^=goToChartButton]").click()'); // click here
            $targets = $this->browser->getTargets();


            $newTarget = null;
            foreach ($targets as $target) {
                $targetType = $target->getTargetInfo('type');
                $targetId = $target->getTargetInfo('targetId');
                if ($targetType === 'page' && $targetId !== $this->page->getSession()->getTargetId()) {
                    $newTarget = $target;
                    break;
                }
            }



            if ($newTarget) {
                $session = $this->browser->getConnection()->createSession($targetId);


        
                // waiting for page loaded
                $session->on('Page.loadEventFired', function () use ($session) {
                    $response = $session->sendMessageSync(new Message('Runtime.evaluate', [
                        'expression' => 'document.documentElement.outerHTML'
                    ]));
                    echo $response['result']['value']; 
                });
            } else {
                echo "Error opening chart page\n";
            }

        } 
    }

The problem is that
Uncaught HeadlessChromium\Exception\CommunicationException: Message could not be sent. Reason: the connection is closed.

How to fix this? And, if it possible, I would prefer to substitute $this->page so that I could use it outside of the function later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant