首页 > 解决方案 > PHP WebDriver - JavaScriptError: Document was unloaded

问题描述

我正在使用带有 Firefox 的 Symfony Panther 来控制和多次提交一个内部的表单<iframe>,其中 iframe 和主文档都具有来自同一个外部主机(比如说 example.org)的 URL。

为此,我使用 awhile检查表单是否可以再次提交。在第一次迭代中,表单已正确提交,但之后我无法再使用对 previous 的引用WebDriver,因为页面已重新加载。

我运行的进程有一个类似这样的代码:

// Long string with JavaScript functions definitions
$sharedFunctions = '...';

// $client is a Panther client
$client->get('https://example.org/page');

// WebDriver of the main page
$mainDriver = $client->getWebDriver();

while (canSubmitTheForm($mainDriver)) {
    // Inserts a <script> to the page with functions that can be used later
    injectSharedFunctions($mainDriver, $sharedFunctions);

    // Opens a modal which has an iframe inside, and finishes once the modal is
    // fully opened (when it's no longer loading the iframe)
    executeAsyncFunction($mainDriver, 'openModal().then(callback)');

    // Gets the iframe after the modal was opened
    $frame = $client->findElement(
        WebDriverBy::cssSelector('.modal iframe#desired-iframe')
    );

    // Returns a driver that controls the iframe
    $frameDriver = $driver->switchTo->frame($frame);

    // Does the same as before but in the iframe's document
    injectSharedFunctions($frameDriver, $sharedFunctions);

    // Fills and submits the form inside the iframe
    executeAsyncFunction($frameDriver, 'fillAndSubmitForm().then(callback)');

    // At this point the page will be refreshed or at least starting to, so
    // apparently $mainDriver is referencing the _unloaded_ document
    // How do I know if the page was refreshed? It has the same URL
    // If the page was refreshed, how do I get the reference to the active document?

    // Here's where the following exception is thrown:
    // Facebook\WebDriver\Exception\JavascriptErrorException: JavaScriptError: Document was unloaded
    $submittedValue = executeAsyncFunction($mainDriver, 'getSubmittedValue().then(callback)');

    doStuffWith($submittedValue);
}

每个 JavaScript 调用都使用 internal document.querySelector,由于文档已卸载,因此似乎无法调用它。

PS:我正在使用 Gecko 驱动程序

标签: phpwebdriversymfony-pantherfacebook-php-webdriverphp-webdriver

解决方案


推荐阅读