chrome-remote-interface icon indicating copy to clipboard operation
chrome-remote-interface copied to clipboard

Clicking inside an iframe?

Open BeatBroccoli opened this issue 11 months ago • 1 comments

Environment

Component Version
Node.js v20.11.1
Client (Chrome/Chromium/...) Google Chrome 122
OS running Node.js Windows 11
OS running the client Windows 11
chrome-remote-interface 0.33.0

Is the client running in a container? NO

Description

Hi, sometimes i cant evaluate scripts inside an iframe. The context doesnt show up. If I open devtools i cant cleary see there is an context but the protocol doesnt provide access to it, at least not via Runtime.executionContextCreated

Example

import * as chromeLauncher from 'chrome-launcher';
import CDP, * as cri from 'chrome-remote-interface';

(async () => {

    let chrome = await chromeLauncher.launch({ port: 9500 });
    let client = await cri.default({ port: chrome.port });

    const { Runtime, Page, Target } = client;
    await Promise.all([Page.enable(), Runtime.enable()]);
    await Target.setAutoAttach({ autoAttach: true, waitForDebuggerOnStart: false });

    Runtime.executionContextCreated(async (evt) => {
        await Runtime.callFunctionOn({
            executionContextId: evt.context.id,
            functionDeclaration: 'function() { alert(document.location.href); let $box = document.querySelector("input"); if($box) $box.click(); return $box; }'
        });
    });

    await Target.targetCreated(({ targetInfo }) => { console.log(`New target created: ${targetInfo.url}`); });
    await Page.navigate({ url: 'https://nopecha.com/demo/cloudflare' });

})();

BeatBroccoli avatar Mar 02 '24 08:03 BeatBroccoli

Few things to try:

  • Call Target.setDiscoverTargets with dicover as true initially
  • When targets are created you will be a given a sessionId to interact with, you need to listen to Target.attachedToTarget events to get these, which should be fired due to setAutoAttach. (In my experience this doesn't always work with iframe targets, you might need to call attachToTarget explicitly)
  • You should call Runtime.enable with any new sessionIds from targets to ensure executionContextCreated is fired from within that session

joeledwardson avatar Apr 07 '24 10:04 joeledwardson