Created
October 19, 2021 08:02
-
-
Save mnanchev/6d45b8b9d6af87d9943e3d448d9d8b67 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const loadUrl = async function(page, url, takeScreenshot) { | |
let stepName = null; | |
let domcontentloaded = false; | |
try { | |
stepName = new URL(url).hostname; | |
} catch (error) { | |
const errorString = `Error parsing url: ${url}. ${error}`; | |
log.error(errorString); | |
/* If we fail to parse the URL, don't emit a metric with a stepName based on it. | |
It may not be a legal CloudWatch metric dimension name and we may not have an alarms | |
setup on the malformed URL stepName. Instead, fail this step which will | |
show up in the logs and will fail the overall canary and alarm on the overall canary | |
success rate. | |
*/ | |
throw error; | |
} | |
await synthetics.executeStep(stepName, async function() { | |
const sanitizedUrl = syntheticsLogHelper.getSanitizedUrl(url); | |
/* You can customize the wait condition here. For instance, using 'networkidle2' or 'networkidle0' to load page completely. | |
networkidle0: Navigation is successful when the page has had no network requests for half a second. This might never happen if page is constantly loading multiple resources. | |
networkidle2: Navigation is successful when the page has no more then 2 network requests for half a second. | |
domcontentloaded: It's fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. Can be used and then add explicit await page.waitFor(timeInMs) | |
*/ | |
const response = await page.goto(url, { waitUntil: ['domcontentloaded'], timeout: 30000 }); | |
if (response) { | |
domcontentloaded = true; | |
const status = response.status(); | |
const statusText = response.statusText(); | |
logResponseString = `Response from url: ${sanitizedUrl} Status: ${status} Status Text: ${statusText}`; | |
//If the response status code is not a 2xx success code | |
if (response.status() < 200 || response.status() > 299) { | |
throw `Failed to load url: ${sanitizedUrl} ${response.status()} ${response.statusText()}`; | |
} | |
} else { | |
const logNoResponseString = `No response returned for url: ${sanitizedUrl}`; | |
log.error(logNoResponseString); | |
throw new Error(logNoResponseString); | |
} | |
}); | |
// Wait for 15 seconds to let page load fully before taking screenshot. | |
if (domcontentloaded && takeScreenshot) { | |
await page.waitFor(15000); | |
await synthetics.takeScreenshot(stepName, 'loaded'); | |
await resetPage(page); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment