pydoll icon indicating copy to clipboard operation
pydoll copied to clipboard

How to use cdp to solve cross-origin iframe

Open link0587 opened this issue 8 months ago • 2 comments

Blocked a frame with origin "file://" from accessing a cross-origin frame

Refer to the following code: https://gist.github.com/imaman/cd7c943e0831a447b1d2b073ede347e2

async function findElementInCrossDomainIframe(port, DOM, Target, iframeSelector, elementSelector) {

    const doc = await DOM.getDocument({depth: 1});
    const iframeQueryResult = await DOM.querySelector({nodeId: doc.root.nodeId, selector: iframeSelector});    
    const iframeDescription = await DOM.describeNode({nodeId: iframeQueryResult.nodeId});
    if (iframeDescription.node.contentDocument) {
        throw new Error('oops. probably same domain');
    }

    // This call is important. Without it, the creation of a new CDP which attached to the iframe
    // (as its target) will fail.
    await Target.getTargets();
    let client2;    
    try {
        client2 = await CDP({port, target: iframeDescription.node.frameId});
        const DOM2 = client2.DOM;

        const doc2 = await DOM2.getDocument({depth: 1});
        const elementQueryResult = await DOM2.querySelector({nodeId: doc2.root.nodeId, selector: elementSelector});
        return await DOM2.describeNode({nodeId: elementQueryResult.nodeId});    
    } finally {
        if (client2) {
            client2.close();
        }
    }
}

link0587 avatar Mar 13 '25 07:03 link0587

Hi @link0587 , you can execute cdp commands using the _execute_command method. Please refer to #67. Also, check the documentation, in the Page domain section, there you can find some examples of how to switch between frames and pages

thalissonvs avatar Mar 13 '25 12:03 thalissonvs

http://jsbin.testim.io/wem

error: Blocked a frame with origin "null" from accessing a cross-origin frame.

document.querySelector('iframe:nth-child(3)').contentWindow.document

ok

document.querySelector('iframe:nth-child(6)').contentWindow.document

link0587 avatar Mar 17 '25 02:03 link0587