Web Page Automation Basics with Plain JavaScript
Before frameworks like Playwright and Selenium, testers automated pages with JavaScript typed straight into the browser console, and the technique is still useful today: to fill a long form during exploratory testing, to extract data from a table, to check every link on a page, or simply to understand what an automation tool does for you. In this lesson you will build a tiny automation toolkit in plain JavaScript: find elements the way users see them (by label, role and text), fill inputs so the app really notices, click, wait for results, extract data and assert. Then you will see its limits, and why a real test framework is the next step. Every example ran in real Chrome against small demo pages.
📖 What You’ll Learn: where to run automation scripts (DevTools console, snippets, bookmarklets), finding elements by id, label, text and role, filling inputs so input and change events fire, clicking and submitting, waiting for elements and text with polling, writing simple assertions, scraping tables and links, checking element visibility, a complete login test in the browser, and the limits of in-page scripts compared with Playwright.
🖥️ Where to Run Automation Scripts
| Place | How | Good for |
|---|---|---|
| DevTools Console | F12 → Console, paste code, press Enter | One-off checks and quick data extraction |
| DevTools Snippets | Sources → Snippets → New snippet, then Ctrl+Enter to run | Saved scripts you reuse, such as “fill the sign-up form” |
| Bookmarklet | A bookmark whose URL starts with javascript: | One-click helpers for teammates |
Playwright page.evaluate() | Runs your function inside the page from a test | Reading state that locators do not expose |
⚠️ Watch out: Only run scripts on applications and environments you are allowed to test, and never paste code from strangers into the console: it runs with your logged-in session and can read or change anything on the page. Browsers show a warning about this for a reason.
🔎 Finding Elements Like a User
CSS selectors such as #user work, but ids change and many elements have none. Users find things by their label, text and role, and those make sturdier locators. These helpers mimic Playwright’s getByLabel, getByText and getByRole in simplified form:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="login">
<label for="user">Username</label>
<input id="user" name="user">
<label for="pass">Password</label>
<input id="pass" name="pass" type="password">
<button type="submit">Sign in</button>
</form>
<p id="message" role="status"></p>
<a href="/forgot">Forgot password?</a>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const $ = (css, root = document) => root.querySelector(css);
const $$ = (css, root = document) => [...root.querySelectorAll(css)];
function byLabel(text) {
const label = $$("label").find((l) => l.textContent.trim() === text);
return label ? document.getElementById(label.htmlFor) ?? label.querySelector("input, select, textarea") : null;
}
function byText(text, css = "a, button, label, p, h1, h2, h3, li, span") {
return $$(css).find((el) => el.textContent.trim() === text) ?? null;
}
function byRole(role, name) {
const implicit = { button: "button, input[type=submit]", link: "a[href]", textbox: "input:not([type]), input[type=text], input[type=email], textarea" };
return $$(`[role="${role}"], ${implicit[role] ?? role}`)
.find((el) => !name || el.textContent.trim() === name || el.getAttribute("aria-label") === name || el.value === name) ?? null;
}
console.log(byLabel("Password"));
console.log(byText("Forgot password?"));
console.log(byRole("button", "Sign in"));
console.log(byRole("link"));
console.log(byLabel("Email")); // no such label -> null
🖥️ Browser console
<input id="pass" name="pass" type="password">
<a href="/forgot">
<button type="submit">
<a href="/forgot">
null
💡 Tip: Chrome’s Console has built-in shortcuts: $("css") is querySelector, $$("css") returns an array of matches, $x("xpath") evaluates XPath, and $0 is the element currently selected in the Elements panel. They only exist in the console, not in page scripts, which is why the example defines its own.
⌨️ Filling Inputs So the App Notices
Setting input.value changes the box, but it fires no events. Apps that listen for input or change, including every React, Vue and Angular form, never see the new value. Dispatch the events yourself after setting the value:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<label for="email">Email</label>
<input id="email">
<p id="preview">Preview: (empty)</p>
<script src="app.js"></script>
</body>
</html>
📄 app.js
// the app updates a preview on every input event
const email = document.querySelector("#email");
email.addEventListener("input", () => {
document.querySelector("#preview").textContent = `Preview: ${email.value}`;
});
// automation attempt 1: only set the value
email.value = "first@sqatools.in";
console.log("1)", document.querySelector("#preview").textContent);
// automation attempt 2: set the value AND fire the events a user would
function fill(input, text) {
input.focus();
input.value = text;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
fill(email, "second@sqatools.in");
console.log("2)", document.querySelector("#preview").textContent);
🖥️ Browser console
1) Preview: (empty)
2) Preview: second@sqatools.in
📌 Note: Some frameworks (React in particular) track the value through the input element’s internal value setter, so a plain value = plus events may still be ignored. The robust fix is Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(input, text) before dispatching input. Playwright’s fill() handles all of this for you, which is one of the reasons to use it.
Checkboxes, selects and clicks
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<label><input type="checkbox" id="terms"> I accept the terms</label>
<select id="plan"><option value="free">Free</option><option value="pro">Pro</option></select>
<button id="next" disabled>Next</button>
<script src="app.js"></script>
</body>
</html>
📄 app.js
// the app: enable Next only when terms are accepted
const terms = document.querySelector("#terms");
const next = document.querySelector("#next");
terms.addEventListener("change", () => { next.disabled = !terms.checked; });
next.addEventListener("click", () => console.log("Next clicked with plan", document.querySelector("#plan").value));
document.querySelector("#plan").addEventListener("change", (e) => console.log("plan changed to", e.target.value));
// the automation
next.click(); // disabled buttons ignore clicks
console.log("disabled?", next.disabled);
terms.click(); // click() toggles a checkbox and fires change
const plan = document.querySelector("#plan");
plan.value = "pro";
plan.dispatchEvent(new Event("change", { bubbles: true }));
next.click();
🖥️ Browser console
disabled? true
plan changed to pro
Next clicked with plan pro
⏳ Waiting for Results
After a click, the result usually arrives later: a request finishes, a framework re-renders. Checking immediately fails. Instead, poll: check a condition repeatedly until it is true or a timeout expires. This is the core idea behind every automation tool’s auto-waiting:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="login">
<label for="user">Username</label>
<input id="user" name="user">
<label for="pass">Password</label>
<input id="pass" name="pass" type="password">
<button type="submit">Sign in</button>
</form>
<p id="message" role="status"></p>
<script type="module" src="app.js"></script>
</body>
</html>
📄 app.js
document.querySelector("#login").addEventListener("submit", (e) => {
e.preventDefault();
const ok = e.target.user.value === "qa_user" && e.target.pass.value === "Test#123";
setTimeout(() => { // the "server" answers after 300 ms
document.querySelector("#message").textContent = ok ? "Welcome, qa_user!" : "Invalid username or password";
}, 300);
});
// ---------- automation helpers ----------
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(condition, { timeout = 3000, interval = 50, message = "condition" } = {}) {
const start = Date.now();
while (Date.now() - start < timeout) {
const result = condition();
if (result) return result;
await sleep(interval);
}
throw new Error(`Timed out after ${timeout} ms waiting for ${message}`);
}
const waitForText = (css, text, timeout) =>
waitFor(() => document.querySelector(css)?.textContent.includes(text), { timeout, message: `"${text}" in ${css}` });
// ---------- the "test" ----------
document.querySelector("#user").value = "qa_user";
document.querySelector("#pass").value = "Test#123";
document.querySelector("#login button").click();
console.log("checked immediately:", JSON.stringify(document.querySelector("#message").textContent));
await waitForText("#message", "Welcome");
console.log("after waiting:", document.querySelector("#message").textContent);
try {
await waitForText("#message", "Dashboard", 500);
} catch (e) {
console.log(e.message);
}
🖥️ Browser console
checked immediately: ""
after waiting: Welcome, qa_user!
Timed out after 500 ms waiting for "Dashboard" in #message
⚠️ Watch out: Never use fixed sleeps (await sleep(3000)) as the way to wait. They are too short on a slow day (flaky failures) and too long on a fast one (slow suites). Wait for a condition with a timeout, as waitFor does.
✅ Simple Assertions
A test is actions plus checks. A tiny expect-style helper makes failures readable:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<h1>Checkout</h1>
<span id="items">3 items</span>
<button id="pay" disabled>Pay ₹2,497</button>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const results = [];
function check(name, actual, expected) {
const pass = Object.is(actual, expected);
results.push({ name, pass });
console.log(`${pass ? "✓" : "✗"} ${name}${pass ? "" : ` — expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`}`);
}
check("page heading", document.querySelector("h1").textContent, "Checkout");
check("item count", document.querySelector("#items").textContent, "3 items");
check("pay button enabled", document.querySelector("#pay").disabled, false);
check("amount on button", document.querySelector("#pay").textContent.includes("₹2,497"), true);
const failed = results.filter((r) => !r.pass).length;
console.log(`${results.length - failed} passed, ${failed} failed`);
🖥️ Browser console
✓ page heading
✓ item count
✗ pay button enabled — expected false, got true
✓ amount on button
3 passed, 1 failed
The Pay button in this page is disabled although the cart has items, so one check fails and says exactly what was expected and what was found. That message is what turns a failed run into a useful bug report.
📤 Extracting Data: Tables, Links and Visibility
Scripts excel at reading pages: turn a table into objects, list every link, or find elements that are present in the DOM but not visible to users. element.checkVisibility() answers “can a user see this?” using the real styles:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<style>
.hidden { display: none; }
</style>
</head>
<body>
<table id="users">
<tr><th>Name</th><th>Role</th><th>Status</th></tr>
<tr><td>Asha</td><td>Admin</td><td>Active</td></tr>
<tr><td>Ravi</td><td>Tester</td><td>Locked</td></tr>
<tr><td>Meera</td><td>Tester</td><td>Active</td></tr>
</table>
<nav>
<a href="/docs">Docs</a>
<a href="https://youtube.com/@SqaToolsByDY">YouTube</a>
<a href="#">Empty link</a>
<a class="hidden" href="/admin">Admin</a>
</nav>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const [header, ...rows] = document.querySelectorAll("#users tr");
const keys = [...header.cells].map((c) => c.textContent.toLowerCase());
const users = rows.map((r) => Object.fromEntries([...r.cells].map((c, i) => [keys[i], c.textContent])));
console.log(users.filter((u) => u.status === "Locked").map((u) => u.name));
const links = [...document.querySelectorAll("a")].map((a) => ({
text: a.textContent,
href: a.getAttribute("href"),
external: a.hostname !== location.hostname,
visible: a.checkVisibility(),
}));
links.forEach((l) => console.log(JSON.stringify(l)));
console.log("suspicious:", links.filter((l) => l.href === "#" || !l.visible).map((l) => l.text));
🖥️ Browser console
["Ravi"]
{"text":"Docs","href":"/docs","external":false,"visible":true}
{"text":"YouTube","href":"https://youtube.com/@SqaToolsByDY","external":true,"visible":true}
{"text":"Empty link","href":"#","external":false,"visible":true}
{"text":"Admin","href":"/admin","external":false,"visible":false}
suspicious: ["Empty link","Admin"]
A next step would be to fetch every internal link and report the ones that do not return 200: a quick broken-link check during exploratory testing.
🧪 Tester Scenario: A Complete Login Test in the Browser
Putting it together: helpers to fill, click and wait, two test cases (invalid and valid login), and a summary. It runs entirely inside the page:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<form id="login">
<label for="user">Username</label>
<input id="user" name="user">
<label for="pass">Password</label>
<input id="pass" name="pass" type="password">
<button type="submit">Sign in</button>
</form>
<p id="message" role="status"></p>
<script type="module" src="app.js"></script>
</body>
</html>
📄 app.js
document.querySelector("#login").addEventListener("submit", (e) => {
e.preventDefault();
const ok = e.target.user.value === "qa_user" && e.target.pass.value === "Test#123";
setTimeout(() => { // the "server" answers after 300 ms
document.querySelector("#message").textContent = ok ? "Welcome, qa_user!" : "Invalid username or password";
}, 300);
});
// ---------- mini framework ----------
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const byLabel = (text) => document.getElementById([...document.querySelectorAll("label")].find((l) => l.textContent === text).htmlFor);
function fill(el, text) {
el.value = text;
el.dispatchEvent(new Event("input", { bubbles: true }));
}
async function waitForText(el, text, timeout = 2000) {
const end = Date.now() + timeout;
while (Date.now() < end) {
if (el.textContent.includes(text)) return;
await sleep(50);
}
throw new Error(`expected "${el.textContent}" to contain "${text}"`);
}
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
// ---------- tests ----------
test("rejects a wrong password", async () => {
fill(byLabel("Username"), "qa_user");
fill(byLabel("Password"), "wrong");
document.querySelector("button[type=submit]").click();
await waitForText(document.querySelector("[role=status]"), "Invalid");
});
test("logs in with valid credentials", async () => {
fill(byLabel("Username"), "qa_user");
fill(byLabel("Password"), "Test#123");
document.querySelector("button[type=submit]").click();
await waitForText(document.querySelector("[role=status]"), "Welcome");
});
test("shows the dashboard (deliberately failing)", async () => {
await waitForText(document.querySelector("[role=status]"), "Dashboard", 400);
});
// ---------- runner ----------
let passed = 0;
for (const t of tests) {
const start = performance.now();
try {
await t.fn();
passed++;
console.log(`✓ ${t.name}`);
} catch (e) {
console.log(`✗ ${t.name}\n ${e.message}`);
}
}
console.log(`${passed}/${tests.length} passed`);
🖥️ Browser console
✓ rejects a wrong password
✓ logs in with valid credentials
✗ shows the dashboard (deliberately failing)
expected "Welcome, qa_user!" to contain "Dashboard"
2/3 passed
Compare it with the same tests in Playwright, where locators, filling, clicking, waiting and assertions are built in and the browser is controlled from outside the page:
📄 login.spec.js (Playwright)
import { test, expect } from "@playwright/test";
test("logs in with valid credentials", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Username").fill("qa_user");
await page.getByLabel("Password").fill("Test#123");
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page.getByRole("status")).toContainText("Welcome");
});
🚧 Limits of In-Page Scripts
| In-page JavaScript | A test framework such as Playwright |
|---|---|
| Stops when the page navigates or reloads (the script is part of the page) | Controls the browser from outside, across navigations |
| Same-origin only: cannot read other sites or cross-origin iframes | Works across origins, frames, tabs and popups |
Events are untrusted (isTrusted: false); file pickers and some features refuse them | Real, trusted mouse and keyboard input |
| No native dialogs, downloads, uploads, permissions or network mocking | Built-in APIs for all of them |
| Hand-written waiting and assertions | Auto-waiting, retrying assertions, traces, reports |
| One browser, by hand | Chromium, Firefox and WebKit in parallel, headless, in CI |
In-page scripting remains a great exploratory-testing and debugging tool, and everything you learned here (selectors, events, waiting, the DOM) is exactly what you need to understand and debug Playwright tests. The Playwright TypeScript course on this site continues from here.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write byLabel(text) that returns the input linked to a label and use it to print the value of the “City” field.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<label for="c">City</label><input id="c" value="Pune">
<script src="app.js"></script>
</body>
</html>📄 app.js
const byLabel = (text) => {
const label = [...document.querySelectorAll("label")].find((l) => l.textContent.trim() === text);
return label && document.getElementById(label.htmlFor);
};
console.log(byLabel("City").value);🖥️ Browser console
PuneQ2. Fill a search box so that its input listener runs, and print what the listener received.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="q">
<script src="app.js"></script>
</body>
</html>📄 app.js
const q = document.querySelector("#q");
q.addEventListener("input", () => console.log("app received:", q.value));
q.value = "playwright";
q.dispatchEvent(new Event("input", { bubbles: true }));🖥️ Browser console
app received: playwrightQ3. Write waitForElement(css, timeout) using polling, and use it to wait for a .done element that appears after 200 ms.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script type="module" src="app.js"></script>
</body>
</html>📄 app.js
async function waitForElement(css, timeout = 2000) {
const end = Date.now() + timeout;
while (Date.now() < end) {
const el = document.querySelector(css);
if (el) return el;
await new Promise((r) => setTimeout(r, 50));
}
throw new Error(`${css} not found`);
}
setTimeout(() => document.body.insertAdjacentHTML("beforeend", "<p class=\"done\">Upload complete</p>"), 200);
console.log((await waitForElement(".done")).textContent);🖥️ Browser console
Upload completeQ4. List the text of every button on the page that is disabled.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button>Save</button><button disabled>Delete</button><button disabled>Export</button>
<script src="app.js"></script>
</body>
</html>📄 app.js
console.log([...document.querySelectorAll("button:disabled")].map((b) => b.textContent));🖥️ Browser console
["Delete","Export"]Q5. Find images without alt text, a common accessibility bug.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<img src="logo.png" alt="SQA Tools logo">
<img src="banner.png">
<img src="icon.png" alt="">
<script src="app.js"></script>
</body>
</html>📄 app.js
const missing = [...document.querySelectorAll("img")].filter((img) => !img.hasAttribute("alt"));
console.log(missing.map((img) => img.getAttribute("src")));🖥️ Browser console
["banner.png"]Q6. Why does a console script that clicks “Next” and then fills the next page’s form stop working after the click?
Show answer
If “Next” loads a new page, the browser discards the current page, including the running script, so the code after the click never runs on the new page. In-page scripts cannot span navigations. Either run the script again on the new page, or use a tool that controls the browser from outside, such as Playwright, where await page.click() followed by page.fill() keeps working across page loads.
🧠 MCQ Quiz: Web Page Automation Basics
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does setting
input.value = "x"NOT do?Answer: Fire input and change events. Dispatch the events yourself or use Playwright fill(). - Which locator is usually the most stable?Answer: The field’s visible label or role and name. It matches what users see.
- What is the right way to wait for a result after a click?Answer: Poll for a condition until it is true or times out. Fixed sleeps are slow and flaky.
- What is
$0in the Chrome console?Answer: The element currently selected in the Elements panel. $1 is the previous selection. - Why does a console script stop after a click that navigates?Answer: The page and its scripts are replaced by the new page. Test frameworks control the browser from outside.
- What does
element.checkVisibility()tell you?Answer: Whether the element is rendered and can be seen. display:none and similar styles make it false. - What is
isTrustedfor events dispatched by your script?Answer: false. Some features only accept trusted events. - Which is a limit of in-page scripts?Answer: They cannot read cross-origin iframes. The same-origin policy applies.
- What is a bookmarklet?Answer: A bookmark whose URL is javascript: code that runs on the current page. Handy for sharing small helpers.
- Which Playwright method runs a function inside the page?Answer: page.evaluate(). Use it to read state that locators do not expose.
💼 Interview Questions and Answers
Q1. What does a tool like Playwright do that you cannot easily do from the browser console?
It drives the browser from outside, so it survives navigations and controls several tabs, frames and origins; it produces trusted input events; it handles dialogs, downloads, uploads, permissions and network interception; it auto-waits for actionability and retries assertions; and it runs headless across Chromium, Firefox and WebKit in parallel with traces and reports. In-page scripts are limited to one page, one origin and untrusted events.
Q2. Why do automation tools wait for elements, and how would you implement waiting yourself?
Modern pages update asynchronously: data arrives from APIs and frameworks re-render, so an element or text may not exist yet at the moment of checking. A wait polls a condition at short intervals (or reacts to DOM changes with MutationObserver) until it is true or a timeout expires, then fails with a clear message. Fixed sleeps are wrong because they are either too short (flaky) or too long (slow).
Q3. You set an input’s value with JavaScript but the form still says the field is required. Why?
The app keeps its own state and updates it from input/change events, which assigning value does not fire. Dispatch an input event with bubbles: true after setting the value (for React, set it through the native value setter first), or use a tool such as Playwright fill() that types like a user.
Q4. How can JavaScript in the console help during manual or exploratory testing?
To fill long forms with test data, extract table data to compare with the database or an API, list all links and check their status, find accessibility issues such as images without alt text or inputs without labels, toggle hidden elements, read localStorage and cookies, and repeat an action many times to look for race conditions, all in seconds and without setting up a framework.
❓ Frequently Asked Questions
🤔 Is browser-console automation a replacement for Selenium or Playwright?
No. It is great for quick exploration and data extraction, but it cannot survive page navigation, work across origins or run unattended in CI. Use a real framework for regression tests.
🤔 What are Chrome DevTools Recorder and snippets?
Snippets store reusable console scripts in DevTools. The Recorder panel records user flows and can export them, including as Puppeteer scripts, which is a good bridge to code-based automation.
🤔 Can I run these scripts on any website?
Technically yes in your own browser, but only test sites you own or have permission to test, respect their terms, and never run unknown code from others in the console.
🤔 Where do I go after this lesson?
Module 13 covers modern and advanced JavaScript features, Module 14 testing with the Node.js test runner and Jest or Vitest, and the Playwright TypeScript course turns these ideas into professional end-to-end tests.
🏁 Summary
- Run quick automation in the DevTools Console, Snippets or bookmarklets; in tests,
page.evaluate()runs code in the page. - Find elements by label, text and role for stable locators; Chrome’s
$,$$and$0help in the console. - Setting
valuefires no events: dispatchinput/change(or use Playwrightfill). - Wait by polling a condition with a timeout, never with fixed sleeps; add small assertions for readable results.
- In-page scripts cannot cross navigations or origins and produce untrusted events, which is why test frameworks drive the browser from outside.
Next, continue with Lesson 63: ES6 to ES2026 Features. This completes Module 12. Module 13 covers modern and advanced JavaScript: ES6 to ES2026 features, functional programming, dates and Intl, performance and design patterns.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in