首页 > 解决方案 > 为什么页面重新加载后框架选择会中断?

问题描述

我正在尝试使用包含框架文档的剧作家检查页面,当我单击按钮时,横幅将出现几分钟。完成后,需要重新加载页面才能使横幅消失。我每 5 分钟自动检查一次,直到我在页面上看不到横幅,但是当我只能为 1 循环执行此操作时,代码会中断。我能做些什么来解决这个问题。

一个可能的解决方案可能是转到 iframe 链接本身,但如果我这样做,文档会中断。我希望避免这样做。如果我手动执行此操作,我不会这样做。

UnhandledPromiseRejectionWarning: frame.evaluate: Execution Context is not available in detached frame (你想评估吗?)

const browser = await chromium.launch({ 
    args: ["--start-maximized", "--disable-notifications",  '--disable-extensions', '--mute-audio'],
    defaultViewport: null,
    devtools: true,
    slowMo: 50,
    downloadsPath: "D:\\Lambda\\projects\\puppeteer_test\\data",
});

// Create a new incognito browser context with user credentials
const context = await browser.newContext({
    acceptDownloads: true,
    viewport: null,
    storageState: JSON.parse(storageState),
})

// Create a new page in a pristine context. 
const page = await context.newPage()

// go to download your information
await page.goto("");

//select child frame
const frameDocUrl = await (await page.waitForSelector("iframe")).getAttribute("src")
const doc = await page.frame({url: frameDocUrl})
await doc.waitForLoadState('domcontentloaded');

/* waitForFile */
// refresh every 5 minute until notice of gathering file is gone 
// then Pending becomes download
const frameUrl = await doc.url()
const fiveMinutes = 300000
let IsGatheringFile = await doc.$("//div[text()='A copy of your information is being created.']") ? true: false
while(IsGatheringFile){
    //reload page
    console.log("going to reload")
    await doc.goto(frameUrl)
    
    // wait for 5 minutes
    console.log(`going to start waiting for 5 min starting in ${Date().split(" ")[4]}`)
    await doc.waitForTimeout(fiveMinutes)
    console.log("finish reloading")

    // check if notice is gone
    IsGatheringFile = await doc.$("//div[text()='A copy of your information is being created.']") ? true: false
}
console.log("finish waiting for data")

console.log("finish reloading the page until the banner is gone")

标签: javascriptplaywright

解决方案


解决方案:在页面刷新/新导航后重新捕获 iframe 上的焦点。

const frameUrl = await doc.url()
await doc.goto(frameUrl)

另外,请注意,您可以使用新的刷新 iframe 将传递给脚本其他部分的变量更新。

旧的hacky修复:

而不是重新加载页面重新加载 iframe。

目前没有 frame.reload 但是这个过程可以通过 frame.goto(frameURL) 来实现

const frameUrl = await doc.url()
await doc.goto(frameUrl)

注意:iframe 可能会中断。重新加载页面可以修复它,但框架将被分离。


推荐阅读