我可以等待 child window 加载第二页吗?

Can I wait for a child window to load the second page?

共有三个可访问页面,http://localhost/parent.htmlhttp://localhost/child1.htmlhttp://localhost/child2.php。 只有 parent.html 对我来说是可编辑的,而其他的则不是。 child2.php 只能通过 child1.html.

的 POST 请求访问

我想做的是从每个 child 页面自动提取数据。 我现在在 parent.html 上,将从这里使用 child window 访问其他两个页面。 但是,等待加载第二页的代码不起作用。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>parent.html</title>
    <script>
    function waitForLoading(targetWindow) {
      return new Promise((resolve, reject) => {
        targetWindow.addEventListener("load", resolve);
      });
    }

    document.addEventListener("DOMContentLoaded", async () => {
      const childWindow = open("child1.html", "_blank");
      await waitForLoading(childWindow);
      // do something with DOM

      childWindow.document.querySelector("form[action='child2.php']").submit();
      await waitForLoading(childWindow); // getting stuck here
      // do something with DOM           // so, this line is unreachable
    });
    </script>
  </head>
  <body>
    <h1>parent.html</h1>
  </body>
</html>

我的问题是:

  1. 为什么代码会卡住?
  2. 如何等待 child window 加载第二页?
  3. 如果不可能,您知道实现目标的任何变通方法吗?

谢谢。

为什么代码会卡住?

即使 child window 加载另一个页面,似乎也不会 运行 loadDOMContentLoaded 第二次或以后。

如何等待 child window 加载第二页?

循环查看页面的加载状态。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>parent.html</title>
    <script>
    function waitFirstPage(targetWindow) {
      return new Promise((resolve, reject) => {
        targetWindow.addEventListener("load", resolve);
      });
    }
    function movePage(targetWindow, action) {
      const originalDocument = targetWindow.document;
      action();
      return new Promise((resolve, reject) => {
        (function loop() {
          if (targetWindow.document !== null
            && targetWindow.document !== originalDocument
            && targetWindow.document.readyState === "complete") {
            resolve();
          }
          setTimeout(loop, 100);
        })();
      });
    }

    document.addEventListener("DOMContentLoaded", async () => {
      const childWindow = open("child1.html", "_blank");
      await waitFirstPage(childWindow);
      // do something with DOM

      await movePage(childWindow, () => {
        childWindow.document.querySelector("form[action='child2.html']").submit();
      });
      // do something with DOM
    });
    </script>
  </head>
  <body>
    <h1>parent.html</h1>
  </body>
</html>

如果不可能,您是否知道实现目标的任何解决方法?

不需要解决方法,因为这是可能的。