SlideShare a Scribd company logo
1 of 53
Download to read offline
Playwright
Automation of
browser
interaction
MeetUp | Code Café | Toolshed – 14 January 2021
Lucas Jellema, CTO & Architect AMIS | Conclusion
Workshop: bit.ly/pw-14jan
Lucas Jellema
CTO for AMIS | Conclusion
Solution Architect
Programmer
MeetUp January 2021 | Playwright browser automation
lucas.jellema@amis.nl | technology.amis.nl | @lucasjellema | lucas-jellema
TL;DR
if you are a programmer and do any work at all with web
browsers, this session can change your professional life.
If you do web development, integration, data engineering,
DevOps automation, test engineering, then make sure to
attend this session. (if you are a designer or solution
architect – you need to be aware as well)
MeetUp January 2021 | Playwright browser automation
Summary
MeetUp January 2021 | Playwright browser automation
Agenda
MeetUp January 2021 | Playwright browser automation
Workshop: bit.ly/pw-14jan
(the road into the) Timesheet Application
MeetUp January 2021 | Playwright browser automation
(the road into the) Timesheet Application
MeetUp January 2021 | Playwright browser automation
Demo – Timesheet Deeplink Bookmark
• Open browser
• Navigate to page
• Login
• <MFA approval on mobile phone>
• Confirm popup
• Click on navigation button
• <new frame opens>
• Click on navigation button
• <timesheet opens>
• Expand Project
• <wait>
• Expand Project
• <wait>
• …
• Start entering hours
Manually
• Click on Shortcut
• <MFA approval on mobile phone>
• <wait>
• Start entering hours
Deeplink Bookmark
MeetUp January 2021 | Playwright browser automation
Deep Link Bookmark – Under the Hood
MeetUp January 2021 | Playwright browser automation
Data gathering from Web Sites and Web Applications
MeetUp January 2021 | Playwright browser automation
Programmatic IMDb Data Scraping
MeetUp January 2021 | Playwright browser automation
REAL Toolshed | December 2020 | Playwright browser automation
Web Application
UI as API
MeetUp January 2021 | Playwright browser automation
Web Application
API
UI as API
MeetUp January 2021 | Playwright browser automation
Web Application
API
Google Translate UI published as API
MeetUp January 2021 | Playwright browser automation
Web Application
API
Translation API to
easily translate a
text from source to
target language
Google Translate UI published as API
MeetUp January 2021 | Playwright browser automation
Web Application
API
WhatsAPI
MeetUp January 2021 | Playwright browser automation
API
Programmatic interaction with WhatsApp
MeetUp January 2021 | Playwright browser automation
Web Application
API
send message
to contact
MeetUp January 2021 | Playwright browser automation
Overview of Playwright
• Make the browser do anything a user can make the browser do plus everything
a developer injecting JavaScript into a live session can activate
• First release January 2020
• 1.0 in May, 1.7 in December
• By Microsoft - the team that first created Puppeteer (while working at Google)
• Open Source – on GitHub
• Support for Chromium, Firefox and WebKit
• Is an alternative to WebDriver
• Primary use case: Web UI Test Automation
MeetUp January 2021 | Playwright browser automation
Playwright
MeetUp January 2021 | Playwright browser automation
Web Application
My Custom Application
HTTP Requests to
fetch HTML, CSS, JS,
images, JSON, SVG,
XML, SSE, files, …
HTTP Requests to
post data, upload files,
…
DOM, JavaScript
context, web workers,
local storage, cookies,
Third Party SaaS
BI Dashboard
Cloud Portal/Console
Custom Application
(web UI on) FTP site
Public Website
Intranet
Playwright – embedded, fully
controlled browser
MeetUp January 2021 | Playwright browser automation
Web Application
My Custom Application
API Calls/HTTP Requests to
fetch HTML, CSS, JS, images,
JSON, SVG, XML, SSE, files,
…
HTTP Requests to
post data, upload files,
…
DOM, JavaScript
context, web workers,
local storage, cookies,
Read DOM elements, fill in fields,
click buttons, trigger events,
manipulate/add DOM elements,
add and execute JavaScript
Playwright – embedded, fully
controlled browser
MeetUp January 2021 | Playwright browser automation
Backend / API
My Custom Application
API Calls/HTTP Requests to
fetch HTML, CSS, JS, images,
JSON, SVG, XML, SSE, files,
…
HTTP Requests to
post data, upload files,
…
DOM, JavaScript
context, web workers,
local storage, cookies,
Read DOM elements, fill in fields,
click buttons, trigger events,
manipulate/add DOM elements,
add and execute JavaScript
Intercept/Mock HTTP
Requests and WebSocket
channels, Make additional
Requests
Web
Application
Overview of Playwright
• The Playwright API is available for
• JavaScript and TypeScript
• Python
• C#
• Go
• Java
• Homepage: playwright.dev
• Docker Container for running
Playwright scripts:
mcr.microsoft.com/playwright:bionic
MeetUp January 2021 | Playwright browser automation
Some Playwright Features
• Headless and Headful
• Bi-directional JavaScript interaction: from Node to Browser and from Browser to Node
context (for example: write to console within the browser or in Node)
• Integration with debugging tools
• Full control across popups, multiple frames and pages (i.e. browser tabs)
• Download and Upload Files
• Get images (and write to file)
• Create Screenshots (.png) and PDF
• Record Playwright Session as Video (MP4)
• Access to WebPerformance APIs
• Social Login (Google, Microsoft Live)
• but not 2FA or Captcha
• Read and Set Cookies and Local Storage, interact with Web Workers,
• Manipulating network requests (HTTP requests sent from the page)
• Headless Recorder (CLI, browser plugin and QA Wolf) to record Playwright script
• Playwright Test Runner and integration with other Test Runner (Mocha, Jest, Jasmine)
MeetUp January 2021 | Playwright browser automation
Many Opportunities Open Up
• Deeplink Bookmarks
• UI Test automation
• including visual regression (use Resemble.js, pixelmatch, Rembrandt.js)
• behavior driven testing, performance & load testing
• Tactical integration
• automation of data retrieval (“Screen Scraping”) and data entry
• Health Checks (monitoring of User Interfaces)
• Automated Reporting
• Customized Web Application
• UI turned API
• Demos and [step by step] Instructions
• RPA – Robotic Process Automation
• automated workflow across multiple systems
• possibly a collaboration between human & robot
• Prototyping (try out finetuning running webapp)
MeetUp January 2021 | Playwright browser automation
Brittle Ethics
• Humans are somewhat flexible with respect to changes in a User Interface
• and do not rely on CSS classes and HTML identifiers
• A Web Application’s user interface(‘s technical implementation) is not a
formal contract such as a REST API
• Changes can occur in the User Interface that may throw the API
implementation created with Playwright
• Ethical considerations: a user interface is not intended for heavy
programmatic use
• use caching and other means to limit the load on the underlying web site
MeetUp January 2021 | Playwright browser automation
Play step-by-step headful Playwright Scenario Acts
To instruct, demonstrate, collaborate or accelerate
• A Playwright scenario in a headful browser can be used to
• demonstrate actions in a web site or app
• provide a tutorial or hands-on instruction on the site or app
• perform quick actions on behalf of the user in a web site or app
• create a combined human  machine workflow
• Playwright script sections (command bundles) can be played on demand
• with annotation
• conditionally
• lightning fast or at human interpretation speed
MeetUp January 2021 | Playwright browser automation
Playwright scenarios – tutorial | demo | documentation | …
• Scenario
• Play Act
• Switch
• Pause
• Reset
• Features
• Callout
• In Situ Balloon
• Type text
• Highlight text
• Scroll elements
in view
• Hover over
elements
• Open new tab / Switch between tabs
MeetUp January 2021 | Playwright browser automation
Generate Daily COVID-19 PowerPoint report
MeetUp January 2021 | Playwright browser automation
Web Application
function
npm module
PptxGenJS
npm module
svg2img
npm module
Jimp
How?
MeetUp January 2021 | Playwright browser automation
Program Code
Hello World of Playwright Demos
//navigate to http://whatsmyuseragent.org and take a screenshot.
MeetUp January 2021 | Playwright browser automation
const { chromium } = require('playwright’);
(async () => {
// start headless embedded browser
const browser = await chromium.launch({headless: true});
const page = await browser.newPage();
// navigate to thesite
await page.goto('http://whatsmyuseragent.org/');
await page.screenshot({ path: `myuseragent-snap.png` });
await browser.close();
})();
Playwright Resources
• Home-page: https://playwright.dev/
• API docs
• Headless Testing &
- theheadless.dev/
- headlesstesting.com/support/start/playwright.html
MeetUp January 2021 | Playwright browser automation
Google Translate UI published as API
MeetUp January 2021 | Playwright browser automation
Web Application
API
'textarea'
'.VIiyi > span > span'
Demo of Translation API (powered by Google Translate)
MeetUp January 2021 | Playwright browser automation
const translate = async (sourceText, sourceLanguage, targetLanguage) => {
const browser = await chromium.launch({ headless: true })
const context = await browser.newContext()
const page = await context.newPage()
await page.goto(`https://translate.google.com/?sl=${sourceLanguage}&tl=${targetLanguage}`)
await page.waitForSelector('textarea')
}
‘textarea’
‘.VIiyi > span > span’
Demo of Translation API (powered by Google Translate)
MeetUp January 2021 | Playwright browser automation
const translate = async (sourceText, sourceLanguage, targetLanguage) => {
const browser = await chromium.launch({ headless: true })
const context = await browser.newContext()
const page = await context.newPage()
await page.goto(`https://translate.google.com/?sl=${sourceLanguage}&tl=${targetLanguage}`)
await page.waitForSelector('textarea')
// set text to translate in the source textarea; note: if length of sourceText > 5000,
// then we should process the sourceText in multiple (parallel processed) slices
await page.fill('textarea', sourceText);
// give Google Translate a little time to perform the translation
await sleep(800)
// get translations from target area (which consists of one or more spans): '.VIiyi > span > span'
const translatedLines = await page.$$eval(".VIiyi > span > span", (spans) => {
return spans.map(span => span.innerText); });
// concatenate the individual lines to a single string
const translation = translatedLines.reduce((accumulator, line) => accumulator + line)
await browser.close()
return translation
}
Selector
• Interaction with forms, fields, buttons, links, text areas, headings, images, …
• actions: read content, fill, type, hover, click (& double click), scroll into view, wait for, tap
• Selectors are expressions to locate, manipulate or get a handle on a page element
• Types of selectors:
• text: page.click('text=Login')
• css: const buttonHandle = page.$('span.submit > button')
• xpath: const title = page.textContent('xpath=//html/body/h1[0]')
• Selectors “pierce” open shadow DOM – for WebComponents – but not iframes
• Selectors can return multiple elements
• operations act on first
• page.$$ returns an array of all matching DOM elements
MeetUp January 2021 | Playwright browser automation
Locating DOM Elements
• CTRL + Shift + I – Browser Developer Tools
• Inspect
• Console: $(‘selector’)
MeetUp January 2021 | Playwright browser automation
Two JavaScript Contexts
MeetUp January 2021 | Playwright browser automation
full access to file system, NPM
modules, network, database, …
No direct access to browser DOM
and JS context
full access to DOM, JavaScript context,
Web APIs, AJAX/WebSocket network calls
leverage browser session’s authentication status
• add/change/remove DOM elements
• handle events
• publish events on DOM elements
• invoke JavaScript functions
2-way bridge
Add Short Cut Key to Web Application
Example: take snapshot of the current page for CTRL+y
MeetUp January 2021 | Playwright browser automation
Web Application
function
snapshotter
This function is handed a Playwright
source object that contains a reference to
the page object. The screenshot()
function on this object is invoked to write
a PNG file with a snapshot of the current
browser’s page content
Add keyup event listener to invoke this proxy
when the shortcut key (ctrl + y) is pressed
function
handleShortCutKey
document.addEventListener
('keyup', handleShortCutKey)
function
snapshotterFunction
.png
Expose NodeJS function as JavaScript function
[proxy] in the browser context of the web page
Inject shortcut key for downloading all images into page
MeetUp January 2021 | Playwright browser automation
let snapshotCount = 0
const snapshotter = async (source) => {
await source.page.screenshot({ path: `${SNAPSHOT_PATH}pageSnapshot${snapshotCount++}.png` });
}
// create a shortcut key (ctrl + b) that triggers the JS function to download all images
const shortCutJS = `async function handleShortCutKey(e) { if ('KeyY'==e.code && e.ctrlKey) {
window.snapshotFunction() ; }}
document.addEventListener('keyup', handleShortCutKey);
`
(async () => {
const browser = await chromium.launch({ headless: false })
const context = await browser.newContext()
// expose a Node function as binding to the page (to be invoked from the function)
await context.exposeBinding('snapshotFunction', snapshotter)
// execute JS snippet for every new page, page reload and navigation
await await context.addInitScript ({ content: shortCutJS })
const page = await context.newPage();
await page.goto(URL);
...
// at this point, the browser will respond to ctrl+y by invoking handleShortCutKey
// that in turn invokes window.snapshotFunction() which is a proxy for function snapshotter in
// the context of the Node application that will write a snapshot PNG file
Manipulate Web Page from Node application
• Add JavaScript to execute for each page load, refresh, navigation
• context.addInitScript(<browser side JavaScript>)
• Add <script> tag to page – with new JavaScript functions and statements to execute
• page.addScriptTag({ content: `console.log('Message from the Outside')` })
• Expose NodeJS function inside the Browser context (on the window object)
• context.exposeBinding('nameOfWindowProperty’, nodeJSFunction)
• Add <style> tag to page - with CSS definitions
• page.addStyleTag({ content: `h1 { color:red}`})
• Execute JavaScript snippet in the Browser context of the web page
• page.evaluate( (name) => { console.log(`name from NodeJS: ${name}`) }, myName)
• Execute JS snippet for a DOM Element located by Playwright (this hides the toolbar)
• page.$eval('#TOOLBAR_ID', (toolbar) => { toolbar.style.display = "none"; })
MeetUp January 2021 | Playwright browser automation
Inject Toolbar into any Web Page or Site loaded into
Playwright embedded browser
• Add floating toolbar with menu options to page after loading or refreshing
• toolbar can be toggled on or off with shortcut key
• options include Save all Images in page (to local file) and take Snapshot
of page
MeetUp January 2021 | Playwright browser automation
github.com/lucasjellema/playwright-scenarios/tree/main/floating_menu
Implementation challenges
• Create a floating, fixed, semi-transparent toolbar — using HTML and CSS
• Add this toolbar — using Playwright — on top of a site or app that is loaded into the
embedded browser
• and ensure that the toolbar stays around / is added again whenever the browser is
navigated to a new page
• Implement the Snapshot function linked to a toolbar option: when the option is
triggered, the Playwright function for taking a snapshot of the page is activated.
• note: the toolbar itself should be hidden at the time of taking the snapshot
• Show and hide the toolbar using a short cut key combination
• Add a toolbar option for saving all images in a page
• Add other features to the toolbar that make life easier around specific or generic web
sites and web applications
• save/restore form entries, record currently selected text, remove all images from
page, play a specific Playwright scenario (demo, instruction, shortcut), ...
MeetUp January 2021 | Playwright browser automation
MeetUp January 2021 | Playwright browser automation
Playwright enables these operations in the Browser Context
• Read and Write (& initialize) Cookies
• Work with Persistent Context (user data directory) in MFA scenarios
• Read and Write (& initialize) Local storage
• Set HTTP Credentials for HTTP Authentication
• Read and Set Locale & Timezone
• Set and Get Geolocation
• Define Viewport (dimensions of visible area) – for browser context or page
• Set Mobile Device – to simulate browser behavior on a mobile device
• Define User Agent (header used in HTTP requests)
• Web Worker (not Service Worker) – monitor and delegate work to
• Monitor, Modify, Abort and Fulfill (aka Mock) HTTP Network requests
• Monitor WebSocket events
• replace WebSocket class with custom class through addInitScript() to mock WebSocket traffic
• Monitor all page events using page.on(‘event’) handlers
• console, dialog, load, fileChoooser, popup, request, response, domcontentloaded, close
MeetUp January 2021 | Playwright browser automation
Testing and Testability of Web Applications
• When using Playwright for automating the test of our custom web application, we can
consider enhancing the testability of our application:
• fixed, meaningful element identifiers and CSS class names
• client-side logic in stand alone JavaScript functions (that do not interact with DOM)
• have functions that set a value on a DOM element also return the value(s) they set
• Testing with Playwright
• one browser (“heavy object”), multiple contexts & multiple pages (light weight objects)
• prepared cookies, local storage, persistent context
• execute JavaScript snippet in browser context to quickly initialize page context (set
field values, execute AJAX calls) instead of corresponding UI manipulation
• take screenshot and make movie during test (and remove when the test succeeds)
• an element handle represents a DOM element and can be inspected for properties
• to speed up, collect “multiple assert findings” in a single object that is evaluated
• instead of running separate Playwright tests for every assert
MeetUp January 2021 | Playwright browser automation
Example of Enhancing Testability
MeetUp January 2021 | Playwright browser automation
Split logic
from
UI/DOM
interaction
Mix logic
with
UI/DOM
interaction
MeetUp January 2021 | Playwright browser automation
Hands On
MeetUp January 2021 | Playwright browser automation
Workshop: bit.ly/pw-14jan
Hands On
MeetUp January 2021 | Playwright browser automation
Workshop: bit.ly/pw-14jan
1. Installation
• In any environment
• Install NodeJS and NPM runtime
• Install Playwright (npm install –D playwright)
• git clone meetup repository from GitHub
• or on Windows 10 with Sandbox enabled
• simple steps to create fresh, isolated and proven hands on environment
• follow instructions in
technology.amis.nl/languages/node-js
/quickly-run-nodejs-demos-in-vanilla-
windows-sandbox-featuring-scoop/
MeetUp January 2021 | Playwright browser automation
Workshop: bit.ly/pw-14jan
2. Run Provided Demonstrations
• inspect and tweak sources
• demos provided
• Quick Steps
• single page, multi tab | window,
take screenshot, generate MP4 | PDF
• Scrape IMDb
• API-fy Google Translate
• Inject Short Cuts
• Inject Floating Toolbar
• Step-by-Step tutorials | demonstrations
• PowerPoint Generator
MeetUp January 2021 | Playwright browser automation
Workshop: bit.ly/pw-14jan
3. Playwright from Scratch – by you
• Create a fresh NodeJS Application
• Copy and paste code to create a browser and a
page
and load a website in the browser
• Add code to interact with the website: click,
scroll, scrape
• Add code to manipulate the page:
• execute JavaScript in the browser and
replace content in the DOM
• Add code to open a second website in a new
browser tab
• Search in the second website
• Assert several conditions – as a first basic test
MeetUp January 2021 | Playwright browser automation
Workshop: bit.ly/pw-14jan

More Related Content

Similar to playwrightmeetup-14jan2021-210114173639.pdf

2014 HTML5 총정리
2014 HTML5 총정리2014 HTML5 총정리
2014 HTML5 총정리Wonsuk Lee
 
Convert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hour
Convert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hourConvert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hour
Convert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hourBrian Culver
 
Desktop apps with node webkit
Desktop apps with node webkitDesktop apps with node webkit
Desktop apps with node webkitPaul Jensen
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGuillaume Laforge
 
Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Lucas Jellema
 
FEDM Meetup: Introducing Mojito
FEDM Meetup: Introducing MojitoFEDM Meetup: Introducing Mojito
FEDM Meetup: Introducing MojitoCaridy Patino
 
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)Brian Culver
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the EnterpriseJames Williams
 
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)Brian Culver
 
Dart Past Your Competition by Getting Your Digital Experience into Market Fas...
Dart Past Your Competition by Getting Your Digital Experience into Market Fas...Dart Past Your Competition by Getting Your Digital Experience into Market Fas...
Dart Past Your Competition by Getting Your Digital Experience into Market Fas...Perficient, Inc.
 
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15GreeceJS
 
Servo: The parallel web engine
Servo: The parallel web engineServo: The parallel web engine
Servo: The parallel web engineBruno Abinader
 
Netbeans65 Osum Slides
Netbeans65 Osum SlidesNetbeans65 Osum Slides
Netbeans65 Osum SlidesAbhishek Gupta
 
[RakutenTechConf2013] [E-2] HTML5 in Rakuten
[RakutenTechConf2013] [E-2] HTML5 in Rakuten[RakutenTechConf2013] [E-2] HTML5 in Rakuten
[RakutenTechConf2013] [E-2] HTML5 in RakutenRakuten Group, Inc.
 
Discover the power of browser developer tools
Discover the power of browser developer toolsDiscover the power of browser developer tools
Discover the power of browser developer toolsylefebvre
 
Net training in bhubaneswar
Net training in bhubaneswar Net training in bhubaneswar
Net training in bhubaneswar litbbsr
 
Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...
Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...
Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...Igalia
 

Similar to playwrightmeetup-14jan2021-210114173639.pdf (20)

2014 HTML5 총정리
2014 HTML5 총정리2014 HTML5 총정리
2014 HTML5 총정리
 
Blazor v1.1
Blazor v1.1Blazor v1.1
Blazor v1.1
 
Convert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hour
Convert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hourConvert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hour
Convert your Full Trust Solutions to the SharePoint Framework (SPFx) in 1 hour
 
Desktop apps with node webkit
Desktop apps with node webkitDesktop apps with node webkit
Desktop apps with node webkit
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and Gaelyk
 
Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...
 
FEDM Meetup: Introducing Mojito
FEDM Meetup: Introducing MojitoFEDM Meetup: Introducing Mojito
FEDM Meetup: Introducing Mojito
 
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
 
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
Convert your Full Trust Solutions to the SharePoint Framework (SPFx)
 
Beyond The MVC
Beyond The MVCBeyond The MVC
Beyond The MVC
 
Dart Past Your Competition by Getting Your Digital Experience into Market Fas...
Dart Past Your Competition by Getting Your Digital Experience into Market Fas...Dart Past Your Competition by Getting Your Digital Experience into Market Fas...
Dart Past Your Competition by Getting Your Digital Experience into Market Fas...
 
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
React Native and the future of web technology (Mark Wilcox) - GreeceJS #15
 
Servo: The parallel web engine
Servo: The parallel web engineServo: The parallel web engine
Servo: The parallel web engine
 
Netbeans65 Osum Slides
Netbeans65 Osum SlidesNetbeans65 Osum Slides
Netbeans65 Osum Slides
 
[RakutenTechConf2013] [E-2] HTML5 in Rakuten
[RakutenTechConf2013] [E-2] HTML5 in Rakuten[RakutenTechConf2013] [E-2] HTML5 in Rakuten
[RakutenTechConf2013] [E-2] HTML5 in Rakuten
 
Discover the power of browser developer tools
Discover the power of browser developer toolsDiscover the power of browser developer tools
Discover the power of browser developer tools
 
Net training in bhubaneswar
Net training in bhubaneswar Net training in bhubaneswar
Net training in bhubaneswar
 
Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...
Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...
Browsers and Web Runtimes for Automotive: Alternatives, Challenges, and Curre...
 
Web Design Trends: 2018 Edition
Web Design Trends: 2018 EditionWeb Design Trends: 2018 Edition
Web Design Trends: 2018 Edition
 

Recently uploaded

VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiVIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位
加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位
加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位obuhobo
 
办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一
办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一
办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一A SSS
 
定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一
定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一
定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一2s3dgmej
 
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一z xss
 
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一A SSS
 
Storytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary PhotographyStorytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary PhotographyOrtega Alikwe
 
Ch. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdfCh. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdfJamalYaseenJameelOde
 
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证nhjeo1gg
 
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一Fs
 
Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607
Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607
Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607dollysharma2066
 
办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改
办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改
办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改yuu sss
 
Black and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdfBlack and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdfpadillaangelina0023
 
办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样
办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样
办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样umasea
 
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012rehmti665
 
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证diploma001
 
NPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdfNPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdfDivyeshPatel234692
 
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...Suhani Kapoor
 
Gray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdfGray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdfpadillaangelina0023
 

Recently uploaded (20)

VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service BhilaiVIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
VIP Call Girl Bhilai Aashi 8250192130 Independent Escort Service Bhilai
 
加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位
加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位
加利福尼亚艺术学院毕业证文凭证书( 咨询 )证书双学位
 
FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974
FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974
FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974
 
办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一
办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一
办理学位证(UoM证书)北安普顿大学毕业证成绩单原版一比一
 
定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一
定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一
定制(NYIT毕业证书)美国纽约理工学院毕业证成绩单原版一比一
 
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
 
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
 
Storytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary PhotographyStorytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary Photography
 
Ch. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdfCh. 9- __Skin, hair and nail Assessment (1).pdf
Ch. 9- __Skin, hair and nail Assessment (1).pdf
 
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
 
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
 
Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607
Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607
Gurgaon Call Girls: Free Delivery 24x7 at Your Doorstep G.G.N = 8377087607
 
办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改
办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改
办澳洲詹姆斯库克大学毕业证成绩单pdf电子版制作修改
 
Black and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdfBlack and White Minimalist Co Letter.pdf
Black and White Minimalist Co Letter.pdf
 
办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样
办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样
办理学位证(纽伦堡大学文凭证书)纽伦堡大学毕业证成绩单原版一模一样
 
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
Call Girls Mukherjee Nagar Delhi reach out to us at ☎ 9711199012
 
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
 
NPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdfNPPE STUDY GUIDE - NOV2021_study_104040.pdf
NPPE STUDY GUIDE - NOV2021_study_104040.pdf
 
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
VIP Call Girls Service Jamshedpur Aishwarya 8250192130 Independent Escort Ser...
 
Gray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdfGray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdf
 

playwrightmeetup-14jan2021-210114173639.pdf

  • 1. Playwright Automation of browser interaction MeetUp | Code Café | Toolshed – 14 January 2021 Lucas Jellema, CTO & Architect AMIS | Conclusion Workshop: bit.ly/pw-14jan
  • 2. Lucas Jellema CTO for AMIS | Conclusion Solution Architect Programmer MeetUp January 2021 | Playwright browser automation lucas.jellema@amis.nl | technology.amis.nl | @lucasjellema | lucas-jellema
  • 3. TL;DR if you are a programmer and do any work at all with web browsers, this session can change your professional life. If you do web development, integration, data engineering, DevOps automation, test engineering, then make sure to attend this session. (if you are a designer or solution architect – you need to be aware as well) MeetUp January 2021 | Playwright browser automation
  • 4. Summary MeetUp January 2021 | Playwright browser automation
  • 5. Agenda MeetUp January 2021 | Playwright browser automation Workshop: bit.ly/pw-14jan
  • 6. (the road into the) Timesheet Application MeetUp January 2021 | Playwright browser automation
  • 7. (the road into the) Timesheet Application MeetUp January 2021 | Playwright browser automation
  • 8. Demo – Timesheet Deeplink Bookmark • Open browser • Navigate to page • Login • <MFA approval on mobile phone> • Confirm popup • Click on navigation button • <new frame opens> • Click on navigation button • <timesheet opens> • Expand Project • <wait> • Expand Project • <wait> • … • Start entering hours Manually • Click on Shortcut • <MFA approval on mobile phone> • <wait> • Start entering hours Deeplink Bookmark MeetUp January 2021 | Playwright browser automation
  • 9. Deep Link Bookmark – Under the Hood MeetUp January 2021 | Playwright browser automation
  • 10. Data gathering from Web Sites and Web Applications MeetUp January 2021 | Playwright browser automation
  • 11. Programmatic IMDb Data Scraping MeetUp January 2021 | Playwright browser automation REAL Toolshed | December 2020 | Playwright browser automation Web Application
  • 12. UI as API MeetUp January 2021 | Playwright browser automation Web Application API
  • 13. UI as API MeetUp January 2021 | Playwright browser automation Web Application API
  • 14. Google Translate UI published as API MeetUp January 2021 | Playwright browser automation Web Application API Translation API to easily translate a text from source to target language
  • 15. Google Translate UI published as API MeetUp January 2021 | Playwright browser automation Web Application API
  • 16. WhatsAPI MeetUp January 2021 | Playwright browser automation API
  • 17. Programmatic interaction with WhatsApp MeetUp January 2021 | Playwright browser automation Web Application API send message to contact
  • 18. MeetUp January 2021 | Playwright browser automation
  • 19. Overview of Playwright • Make the browser do anything a user can make the browser do plus everything a developer injecting JavaScript into a live session can activate • First release January 2020 • 1.0 in May, 1.7 in December • By Microsoft - the team that first created Puppeteer (while working at Google) • Open Source – on GitHub • Support for Chromium, Firefox and WebKit • Is an alternative to WebDriver • Primary use case: Web UI Test Automation MeetUp January 2021 | Playwright browser automation
  • 20. Playwright MeetUp January 2021 | Playwright browser automation Web Application My Custom Application HTTP Requests to fetch HTML, CSS, JS, images, JSON, SVG, XML, SSE, files, … HTTP Requests to post data, upload files, … DOM, JavaScript context, web workers, local storage, cookies, Third Party SaaS BI Dashboard Cloud Portal/Console Custom Application (web UI on) FTP site Public Website Intranet
  • 21. Playwright – embedded, fully controlled browser MeetUp January 2021 | Playwright browser automation Web Application My Custom Application API Calls/HTTP Requests to fetch HTML, CSS, JS, images, JSON, SVG, XML, SSE, files, … HTTP Requests to post data, upload files, … DOM, JavaScript context, web workers, local storage, cookies, Read DOM elements, fill in fields, click buttons, trigger events, manipulate/add DOM elements, add and execute JavaScript
  • 22. Playwright – embedded, fully controlled browser MeetUp January 2021 | Playwright browser automation Backend / API My Custom Application API Calls/HTTP Requests to fetch HTML, CSS, JS, images, JSON, SVG, XML, SSE, files, … HTTP Requests to post data, upload files, … DOM, JavaScript context, web workers, local storage, cookies, Read DOM elements, fill in fields, click buttons, trigger events, manipulate/add DOM elements, add and execute JavaScript Intercept/Mock HTTP Requests and WebSocket channels, Make additional Requests Web Application
  • 23. Overview of Playwright • The Playwright API is available for • JavaScript and TypeScript • Python • C# • Go • Java • Homepage: playwright.dev • Docker Container for running Playwright scripts: mcr.microsoft.com/playwright:bionic MeetUp January 2021 | Playwright browser automation
  • 24. Some Playwright Features • Headless and Headful • Bi-directional JavaScript interaction: from Node to Browser and from Browser to Node context (for example: write to console within the browser or in Node) • Integration with debugging tools • Full control across popups, multiple frames and pages (i.e. browser tabs) • Download and Upload Files • Get images (and write to file) • Create Screenshots (.png) and PDF • Record Playwright Session as Video (MP4) • Access to WebPerformance APIs • Social Login (Google, Microsoft Live) • but not 2FA or Captcha • Read and Set Cookies and Local Storage, interact with Web Workers, • Manipulating network requests (HTTP requests sent from the page) • Headless Recorder (CLI, browser plugin and QA Wolf) to record Playwright script • Playwright Test Runner and integration with other Test Runner (Mocha, Jest, Jasmine) MeetUp January 2021 | Playwright browser automation
  • 25. Many Opportunities Open Up • Deeplink Bookmarks • UI Test automation • including visual regression (use Resemble.js, pixelmatch, Rembrandt.js) • behavior driven testing, performance & load testing • Tactical integration • automation of data retrieval (“Screen Scraping”) and data entry • Health Checks (monitoring of User Interfaces) • Automated Reporting • Customized Web Application • UI turned API • Demos and [step by step] Instructions • RPA – Robotic Process Automation • automated workflow across multiple systems • possibly a collaboration between human & robot • Prototyping (try out finetuning running webapp) MeetUp January 2021 | Playwright browser automation
  • 26. Brittle Ethics • Humans are somewhat flexible with respect to changes in a User Interface • and do not rely on CSS classes and HTML identifiers • A Web Application’s user interface(‘s technical implementation) is not a formal contract such as a REST API • Changes can occur in the User Interface that may throw the API implementation created with Playwright • Ethical considerations: a user interface is not intended for heavy programmatic use • use caching and other means to limit the load on the underlying web site MeetUp January 2021 | Playwright browser automation
  • 27. Play step-by-step headful Playwright Scenario Acts To instruct, demonstrate, collaborate or accelerate • A Playwright scenario in a headful browser can be used to • demonstrate actions in a web site or app • provide a tutorial or hands-on instruction on the site or app • perform quick actions on behalf of the user in a web site or app • create a combined human  machine workflow • Playwright script sections (command bundles) can be played on demand • with annotation • conditionally • lightning fast or at human interpretation speed MeetUp January 2021 | Playwright browser automation
  • 28. Playwright scenarios – tutorial | demo | documentation | … • Scenario • Play Act • Switch • Pause • Reset • Features • Callout • In Situ Balloon • Type text • Highlight text • Scroll elements in view • Hover over elements • Open new tab / Switch between tabs MeetUp January 2021 | Playwright browser automation
  • 29. Generate Daily COVID-19 PowerPoint report MeetUp January 2021 | Playwright browser automation Web Application function npm module PptxGenJS npm module svg2img npm module Jimp
  • 30. How? MeetUp January 2021 | Playwright browser automation Program Code
  • 31. Hello World of Playwright Demos //navigate to http://whatsmyuseragent.org and take a screenshot. MeetUp January 2021 | Playwright browser automation const { chromium } = require('playwright’); (async () => { // start headless embedded browser const browser = await chromium.launch({headless: true}); const page = await browser.newPage(); // navigate to thesite await page.goto('http://whatsmyuseragent.org/'); await page.screenshot({ path: `myuseragent-snap.png` }); await browser.close(); })();
  • 32. Playwright Resources • Home-page: https://playwright.dev/ • API docs • Headless Testing & - theheadless.dev/ - headlesstesting.com/support/start/playwright.html MeetUp January 2021 | Playwright browser automation
  • 33. Google Translate UI published as API MeetUp January 2021 | Playwright browser automation Web Application API 'textarea' '.VIiyi > span > span'
  • 34. Demo of Translation API (powered by Google Translate) MeetUp January 2021 | Playwright browser automation const translate = async (sourceText, sourceLanguage, targetLanguage) => { const browser = await chromium.launch({ headless: true }) const context = await browser.newContext() const page = await context.newPage() await page.goto(`https://translate.google.com/?sl=${sourceLanguage}&tl=${targetLanguage}`) await page.waitForSelector('textarea') } ‘textarea’ ‘.VIiyi > span > span’
  • 35. Demo of Translation API (powered by Google Translate) MeetUp January 2021 | Playwright browser automation const translate = async (sourceText, sourceLanguage, targetLanguage) => { const browser = await chromium.launch({ headless: true }) const context = await browser.newContext() const page = await context.newPage() await page.goto(`https://translate.google.com/?sl=${sourceLanguage}&tl=${targetLanguage}`) await page.waitForSelector('textarea') // set text to translate in the source textarea; note: if length of sourceText > 5000, // then we should process the sourceText in multiple (parallel processed) slices await page.fill('textarea', sourceText); // give Google Translate a little time to perform the translation await sleep(800) // get translations from target area (which consists of one or more spans): '.VIiyi > span > span' const translatedLines = await page.$$eval(".VIiyi > span > span", (spans) => { return spans.map(span => span.innerText); }); // concatenate the individual lines to a single string const translation = translatedLines.reduce((accumulator, line) => accumulator + line) await browser.close() return translation }
  • 36. Selector • Interaction with forms, fields, buttons, links, text areas, headings, images, … • actions: read content, fill, type, hover, click (& double click), scroll into view, wait for, tap • Selectors are expressions to locate, manipulate or get a handle on a page element • Types of selectors: • text: page.click('text=Login') • css: const buttonHandle = page.$('span.submit > button') • xpath: const title = page.textContent('xpath=//html/body/h1[0]') • Selectors “pierce” open shadow DOM – for WebComponents – but not iframes • Selectors can return multiple elements • operations act on first • page.$$ returns an array of all matching DOM elements MeetUp January 2021 | Playwright browser automation
  • 37. Locating DOM Elements • CTRL + Shift + I – Browser Developer Tools • Inspect • Console: $(‘selector’) MeetUp January 2021 | Playwright browser automation
  • 38. Two JavaScript Contexts MeetUp January 2021 | Playwright browser automation full access to file system, NPM modules, network, database, … No direct access to browser DOM and JS context full access to DOM, JavaScript context, Web APIs, AJAX/WebSocket network calls leverage browser session’s authentication status • add/change/remove DOM elements • handle events • publish events on DOM elements • invoke JavaScript functions 2-way bridge
  • 39. Add Short Cut Key to Web Application Example: take snapshot of the current page for CTRL+y MeetUp January 2021 | Playwright browser automation Web Application function snapshotter This function is handed a Playwright source object that contains a reference to the page object. The screenshot() function on this object is invoked to write a PNG file with a snapshot of the current browser’s page content Add keyup event listener to invoke this proxy when the shortcut key (ctrl + y) is pressed function handleShortCutKey document.addEventListener ('keyup', handleShortCutKey) function snapshotterFunction .png Expose NodeJS function as JavaScript function [proxy] in the browser context of the web page
  • 40. Inject shortcut key for downloading all images into page MeetUp January 2021 | Playwright browser automation let snapshotCount = 0 const snapshotter = async (source) => { await source.page.screenshot({ path: `${SNAPSHOT_PATH}pageSnapshot${snapshotCount++}.png` }); } // create a shortcut key (ctrl + b) that triggers the JS function to download all images const shortCutJS = `async function handleShortCutKey(e) { if ('KeyY'==e.code && e.ctrlKey) { window.snapshotFunction() ; }} document.addEventListener('keyup', handleShortCutKey); ` (async () => { const browser = await chromium.launch({ headless: false }) const context = await browser.newContext() // expose a Node function as binding to the page (to be invoked from the function) await context.exposeBinding('snapshotFunction', snapshotter) // execute JS snippet for every new page, page reload and navigation await await context.addInitScript ({ content: shortCutJS }) const page = await context.newPage(); await page.goto(URL); ... // at this point, the browser will respond to ctrl+y by invoking handleShortCutKey // that in turn invokes window.snapshotFunction() which is a proxy for function snapshotter in // the context of the Node application that will write a snapshot PNG file
  • 41. Manipulate Web Page from Node application • Add JavaScript to execute for each page load, refresh, navigation • context.addInitScript(<browser side JavaScript>) • Add <script> tag to page – with new JavaScript functions and statements to execute • page.addScriptTag({ content: `console.log('Message from the Outside')` }) • Expose NodeJS function inside the Browser context (on the window object) • context.exposeBinding('nameOfWindowProperty’, nodeJSFunction) • Add <style> tag to page - with CSS definitions • page.addStyleTag({ content: `h1 { color:red}`}) • Execute JavaScript snippet in the Browser context of the web page • page.evaluate( (name) => { console.log(`name from NodeJS: ${name}`) }, myName) • Execute JS snippet for a DOM Element located by Playwright (this hides the toolbar) • page.$eval('#TOOLBAR_ID', (toolbar) => { toolbar.style.display = "none"; }) MeetUp January 2021 | Playwright browser automation
  • 42. Inject Toolbar into any Web Page or Site loaded into Playwright embedded browser • Add floating toolbar with menu options to page after loading or refreshing • toolbar can be toggled on or off with shortcut key • options include Save all Images in page (to local file) and take Snapshot of page MeetUp January 2021 | Playwright browser automation github.com/lucasjellema/playwright-scenarios/tree/main/floating_menu
  • 43. Implementation challenges • Create a floating, fixed, semi-transparent toolbar — using HTML and CSS • Add this toolbar — using Playwright — on top of a site or app that is loaded into the embedded browser • and ensure that the toolbar stays around / is added again whenever the browser is navigated to a new page • Implement the Snapshot function linked to a toolbar option: when the option is triggered, the Playwright function for taking a snapshot of the page is activated. • note: the toolbar itself should be hidden at the time of taking the snapshot • Show and hide the toolbar using a short cut key combination • Add a toolbar option for saving all images in a page • Add other features to the toolbar that make life easier around specific or generic web sites and web applications • save/restore form entries, record currently selected text, remove all images from page, play a specific Playwright scenario (demo, instruction, shortcut), ... MeetUp January 2021 | Playwright browser automation
  • 44. MeetUp January 2021 | Playwright browser automation
  • 45. Playwright enables these operations in the Browser Context • Read and Write (& initialize) Cookies • Work with Persistent Context (user data directory) in MFA scenarios • Read and Write (& initialize) Local storage • Set HTTP Credentials for HTTP Authentication • Read and Set Locale & Timezone • Set and Get Geolocation • Define Viewport (dimensions of visible area) – for browser context or page • Set Mobile Device – to simulate browser behavior on a mobile device • Define User Agent (header used in HTTP requests) • Web Worker (not Service Worker) – monitor and delegate work to • Monitor, Modify, Abort and Fulfill (aka Mock) HTTP Network requests • Monitor WebSocket events • replace WebSocket class with custom class through addInitScript() to mock WebSocket traffic • Monitor all page events using page.on(‘event’) handlers • console, dialog, load, fileChoooser, popup, request, response, domcontentloaded, close MeetUp January 2021 | Playwright browser automation
  • 46. Testing and Testability of Web Applications • When using Playwright for automating the test of our custom web application, we can consider enhancing the testability of our application: • fixed, meaningful element identifiers and CSS class names • client-side logic in stand alone JavaScript functions (that do not interact with DOM) • have functions that set a value on a DOM element also return the value(s) they set • Testing with Playwright • one browser (“heavy object”), multiple contexts & multiple pages (light weight objects) • prepared cookies, local storage, persistent context • execute JavaScript snippet in browser context to quickly initialize page context (set field values, execute AJAX calls) instead of corresponding UI manipulation • take screenshot and make movie during test (and remove when the test succeeds) • an element handle represents a DOM element and can be inspected for properties • to speed up, collect “multiple assert findings” in a single object that is evaluated • instead of running separate Playwright tests for every assert MeetUp January 2021 | Playwright browser automation
  • 47. Example of Enhancing Testability MeetUp January 2021 | Playwright browser automation Split logic from UI/DOM interaction Mix logic with UI/DOM interaction
  • 48. MeetUp January 2021 | Playwright browser automation
  • 49. Hands On MeetUp January 2021 | Playwright browser automation Workshop: bit.ly/pw-14jan
  • 50. Hands On MeetUp January 2021 | Playwright browser automation Workshop: bit.ly/pw-14jan
  • 51. 1. Installation • In any environment • Install NodeJS and NPM runtime • Install Playwright (npm install –D playwright) • git clone meetup repository from GitHub • or on Windows 10 with Sandbox enabled • simple steps to create fresh, isolated and proven hands on environment • follow instructions in technology.amis.nl/languages/node-js /quickly-run-nodejs-demos-in-vanilla- windows-sandbox-featuring-scoop/ MeetUp January 2021 | Playwright browser automation Workshop: bit.ly/pw-14jan
  • 52. 2. Run Provided Demonstrations • inspect and tweak sources • demos provided • Quick Steps • single page, multi tab | window, take screenshot, generate MP4 | PDF • Scrape IMDb • API-fy Google Translate • Inject Short Cuts • Inject Floating Toolbar • Step-by-Step tutorials | demonstrations • PowerPoint Generator MeetUp January 2021 | Playwright browser automation Workshop: bit.ly/pw-14jan
  • 53. 3. Playwright from Scratch – by you • Create a fresh NodeJS Application • Copy and paste code to create a browser and a page and load a website in the browser • Add code to interact with the website: click, scroll, scrape • Add code to manipulate the page: • execute JavaScript in the browser and replace content in the DOM • Add code to open a second website in a new browser tab • Search in the second website • Assert several conditions – as a first basic test MeetUp January 2021 | Playwright browser automation Workshop: bit.ly/pw-14jan