Best JavaScript code snippet using wpt
helper.sub.js
Source:helper.sub.js
1// Helpers called on the main test HTMLs.2// Functions in `RemoteContext.execute_script()`'s 1st argument are evaluated3// on the executors (`executor.html`), and helpers available on the executors4// are defined in `executor.html`.5const originSameOrigin =6 location.protocol === 'http:' ?7 'http://{{host}}:{{ports[http][0]}}' :8 'https://{{host}}:{{ports[https][0]}}';9const originSameSite =10 location.protocol === 'http:' ?11 'http://{{host}}:{{ports[http][1]}}' :12 'https://{{host}}:{{ports[https][1]}}';13const originCrossSite =14 location.protocol === 'http:' ?15 'http://{{hosts[alt][www]}}:{{ports[http][0]}}' :16 'https://{{hosts[alt][www]}}:{{ports[https][0]}}';17const executorPath =18 '/html/browsers/browsing-the-web/back-forward-cache/resources/executor.html?uuid=';19// Asserts that the executor `target` is (or isn't, respectively)20// restored from BFCache. These should be used in the following fashion:21// 1. Call prepareNavigation() on the executor `target`.22// 2. Navigate the executor to another page.23// 3. Navigate back to the executor `target`.24// 4. Call assert_bfcached() or assert_not_bfcached() on the main test HTML.25async function assert_bfcached(target) {26 const status = await getBFCachedStatus(target);27 assert_implements_optional(status === 'BFCached',28 "Should be BFCached but actually wasn't");29}30async function assert_not_bfcached(target) {31 const status = await getBFCachedStatus(target);32 assert_implements(status !== 'BFCached',33 'Should not be BFCached but actually was');34}35async function getBFCachedStatus(target) {36 const [loadCount, isPageshowFired, isPageshowPersisted] =37 await target.execute_script(() => [38 window.loadCount, window.isPageshowFired, window.isPageshowPersisted]);39 if (loadCount === 1 && isPageshowFired === true &&40 isPageshowPersisted === true) {41 return 'BFCached';42 } else if (loadCount === 2 && isPageshowFired === false) {43 return 'Not BFCached';44 } else {45 // This can occur for example when this is called before first navigating46 // away (loadCount = 1, isPageshowFired = false), e.g. when47 // 1. sending a script for navigation and then48 // 2. calling getBFCachedStatus() without waiting for the completion of49 // the script on the `target` page.50 assert_unreached(51 `Got unexpected BFCache status: loadCount = ${loadCount}, ` +52 `isPageshowFired = ${isPageshowFired}, ` +53 `isPageshowPersisted = ${isPageshowPersisted}`);54 }55}56// Always call `await remoteContext.execute_script(waitForPageShow);` after57// triggering to navigation to the page, to wait for pageshow event on the58// remote context.59const waitForPageShow = () => window.pageShowPromise;60// Run a test that navigates A->B->A:61// 1. Page A is opened by `params.openFunc(url)`.62// 2. `params.funcBeforeNavigation` is executed on page A.63// 3. The window is navigated to page B on `params.targetOrigin`.64// 4. The window is back navigated to page A (expecting BFCached).65//66// Events `params.events` (an array of strings) are observed on page A and67// `params.expectedEvents` (an array of strings) is expected to be recorded.68// See `event-recorder.js` for event recording.69//70// Parameters can be omitted. See `defaultParams` below for default.71function runEventTest(params, description) {72 const defaultParams = {73 openFunc(url) {74 window.open(75 `${url}&events=${this.events.join(',')}`,76 '_blank',77 'noopener'78 )79 },80 events: ['pagehide', 'pageshow', 'load'],81 expectedEvents: [82 'window.load',83 'window.pageshow',84 'window.pagehide.persisted',85 'window.pageshow.persisted'86 ],87 async funcAfterAssertion(pageA) {88 assert_array_equals(89 await pageA.execute_script(() => getRecordedEvents()),90 this.expectedEvents);91 }92 }93 // Apply defaults.94 params = { ...defaultParams, ...params };95 runBfcacheTest(params, description);96}97async function navigateAndThenBack(pageA, pageB, urlB) {98 await pageA.execute_script(99 (url) => {100 prepareNavigation(() => {101 location.href = url;102 });103 },104 [urlB]105 );106 await pageB.execute_script(waitForPageShow);107 await pageB.execute_script(108 () => {109 prepareNavigation(() => { history.back(); });110 }111 );112 await pageA.execute_script(waitForPageShow);113}114function runBfcacheTest(params, description) {115 const defaultParams = {116 openFunc: url => window.open(url, '_blank', 'noopener'),117 scripts: [],118 funcBeforeNavigation: () => {},119 targetOrigin: originCrossSite,120 shouldBeCached: true,121 funcAfterAssertion: () => {},122 }123 // Apply defaults.124 params = {...defaultParams, ...params };125 promise_test(async t => {126 const pageA = new RemoteContext(token());127 const pageB = new RemoteContext(token());128 const urlA = executorPath + pageA.context_id;129 const urlB = params.targetOrigin + executorPath + pageB.context_id;130 params.openFunc(urlA);131 await pageA.execute_script(waitForPageShow);132 for (const src of params.scripts) {133 await pageA.execute_script((src) => {134 const script = document.createElement("script");135 script.src = src;136 document.head.append(script);137 return new Promise(resolve => script.onload = resolve);138 }, [src]);139 }140 await pageA.execute_script(params.funcBeforeNavigation);141 await navigateAndThenBack(pageA, pageB, urlB);142 if (params.shouldBeCached) {143 await assert_bfcached(pageA);144 } else {145 await assert_not_bfcached(pageA);146 }147 if (params.funcAfterAssertion) {148 await params.funcAfterAssertion(pageA, pageB);149 }150 }, description);...
otworz_strony.py
Source:otworz_strony.py
...1011driver = webdriver.Chrome(options=options)1213"""14driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")15driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'})16print(driver.execute_script("return navigator.userAgent;"))17"""1819driver.get("https://phenotype.pl/")20driver.execute_script('''window.open("https://the100clth.pl/","_blank");''')21driver.execute_script('''window.open("https://animalswave.com/","_blank");''')22driver.execute_script('''window.open("https://relab.store/","_blank");''')23driver.execute_script('''window.open("https://hazel21.com/","_blank");''')24driver.execute_script('''window.open("https://zoology.pl/","_blank");''')25driver.execute_script('''window.open("https://premieresociety.com/pl/","_blank");''')26driver.execute_script('''window.open("https://hillswear.com/","_blank");''')27driver.execute_script('''window.open("https://www.snipes.pl/","_blank");''')28driver.execute_script('''window.open("https://www.alexanderbigwig.com/","_blank");''')29driver.execute_script('''window.open("https://inrablew.pl/pl/","_blank");''')30driver.execute_script('''window.open("https://mindstate.pl/pl/","_blank");''')31driver.execute_script('''window.open("https://zillamob.com/","_blank");''')32driver.execute_script('''window.open("https://majors.pl/","_blank");''')33driver.execute_script('''window.open("https://rareeverywhere.pl/","_blank");''')34driver.execute_script('''window.open("https://ideologyproject.com/store/","_blank");''')35driver.execute_script('''window.open("https://enragecustoms.pl/shop/","_blank");''')36driver.execute_script('''window.open("https://an-appendage.com/?v=9b7d173b068d&c=2a7c42566189","_blank");''')37driver.execute_script('''window.open("https://www.7more7.com/","_blank");''')38driver.execute_script('''window.open("https://velpa.pl/","_blank");''')39driver.execute_script('''window.open("https://debrande.pl/","_blank");''')40driver.execute_script('''window.open("https://www.gugushop.pl/","_blank");''')41driver.execute_script('''window.open("https://www.reserved.com/pl/pl/","_blank");''')42driver.execute_script('''window.open("https://www.zara.com/pl/","_blank");''')43driver.execute_script('''window.open("https://www.vangraaf.com/pl/","_blank");''')44driver.execute_script('''window.open("https://www.vitkac.com/pl","_blank");''')45driver.execute_script('''window.open("https://www.zalando-lounge.pl/event#","_blank");''')46driver.execute_script('''window.open("https://www.moliera2.com/","_blank");''')47driver.execute_script('''window.open("https://gomez.pl/pl/dla_niego","_blank");''')48driver.execute_script('''window.open("https://modivo.pl/m/mezczyzni.html","_blank");''')49driver.execute_script('''window.open("https://www.guess.eu/pl-pl/homepage","_blank");''')50driver.execute_script('''window.open("https://www.asos.com/pl/mezczyzni/","_blank");''')51driver.execute_script('''window.open("https://www.forpro.pl/","_blank");''')52driver.execute_script('''window.open("https://www.aboutyou.pl/","_blank");''')53driver.execute_script('''window.open("https://www.ataf.pl/pl/","_blank");''')54driver.execute_script('''window.open("https://www.nike.com/pl/","_blank");''')55driver.execute_script('''window.open("https://www.adidas.pl/","_blank");''')56driver.execute_script('''window.open("https://answear.com/c/on","_blank");''')57driver.execute_script('''window.open("https://www.peek-cloppenburg.pl/mezczyzni/","_blank");''')58driver.execute_script('''window.open("https://skstore.eu/pl","_blank");''')59driver.execute_script('''window.open("https://streetsupply.pl/","_blank");''')60driver.execute_script('''window.open("https://www.mandmdirect.pl/","_blank");''')61driver.execute_script('''window.open("https://worldbox.pl/","_blank");''')62driver.execute_script('''window.open("https://streetstyle24.pl/","_blank");''')63driver.execute_script('''window.open("https://eastendshop.com/pl/men-landing","_blank");''')64driver.execute_script('''window.open("https://runcolors.pl/","_blank");''')65driver.execute_script('''window.open("https://www.luisaviaroma.com/","_blank");''')66driver.execute_script('''window.open("https://warsawsneakerstore.com/","_blank");''')67driver.execute_script('''window.open("https://www.caliroots.com/pl","_blank");''')
...
test_execute_script.py
Source:test_execute_script.py
...5from errors import JavascriptException, MarionetteException6class TestExecuteContent(MarionetteTestCase):7 def test_stack_trace(self):8 try:9 self.marionette.execute_script("""10 let a = 1;11 return b;12 """)13 self.assertFalse(True)14 except JavascriptException, inst:15 self.assertTrue('return b' in inst.stacktrace)16 def test_execute_simple(self):17 self.assertEqual(1, self.marionette.execute_script("return 1;"))18 def test_check_window(self):19 self.assertTrue(self.marionette.execute_script("return (window !=null && window != undefined);"))20 def test_execute_no_return(self):21 self.assertEqual(self.marionette.execute_script("1;"), None)22 def test_execute_js_exception(self):23 self.assertRaises(JavascriptException,24 self.marionette.execute_script, "return foo(bar);")25 def test_execute_permission(self):26 self.assertRaises(JavascriptException,27 self.marionette.execute_script,28 """29let prefs = Components.classes["@mozilla.org/preferences-service;1"]30 .getService(Components.interfaces.nsIPrefBranch);31""")32 def test_complex_return_values(self):33 self.assertEqual(self.marionette.execute_script("return [1, 2];"), [1, 2])34 self.assertEqual(self.marionette.execute_script("return {'foo': 'bar', 'fizz': 'fazz'};"),35 {'foo': 'bar', 'fizz': 'fazz'})36 self.assertEqual(self.marionette.execute_script("return [1, {'foo': 'bar'}, 2];"),37 [1, {'foo': 'bar'}, 2])38 self.assertEqual(self.marionette.execute_script("return {'foo': [1, 'a', 2]};"),39 {'foo': [1, 'a', 2]})40 def test_sandbox_reuse(self):41 # Sandboxes between `execute_script()` invocations are shared.42 self.marionette.execute_script("this.foobar = [23, 42];")43 self.assertEqual(self.marionette.execute_script("return this.foobar;", new_sandbox=False), [23, 42])44 self.marionette.execute_script("global.barfoo = [42, 23];")45 self.assertEqual(self.marionette.execute_script("return global.barfoo;", new_sandbox=False), [42, 23])46 def test_that_we_can_pass_in_floats(self):47 expected_result = 1.248 result = self.marionette.execute_script("return arguments[0]",49 [expected_result])50 self.assertTrue(isinstance(result, float))51 self.assertEqual(result, expected_result)52class TestExecuteChrome(TestExecuteContent):53 def setUp(self):54 super(TestExecuteChrome, self).setUp()55 self.marionette.set_context("chrome")56 def test_execute_permission(self):57 self.assertEqual(1, self.marionette.execute_script("var c = Components.classes;return 1;"))58 def test_sandbox_reuse(self):...
setup.py
Source:setup.py
...11 f"\tuser='{user}',\n",12 f"\tpassword='{password}',\n",13 f"\tdatabase='univ_db'\n)"])14# https://stackoverflow.com/questions/745538/create-function-through-mysqldb15def execute_script(fname, db):16 delimiter = ';'17 statement = ""18 with open(fname, encoding='utf-8') as f:19 for line in f.readlines():20 line = line.strip()21 if line.startswith('delimiter'):22 delimiter = line[10:]23 else:24 statement += line + '\n'25 if line.endswith(delimiter):26 statement = statement.strip().strip(delimiter)27 with db.cursor() as cursor:28 try:29 cursor.execute(statement)30 db.commit()31 statement = ""32 except cursor.Error as e:33 print(f"{fname} - error applying ({str(e)})\nstatement:{statement}\nterminating...")34 sys.exit(1)35if __name__ == '__main__':36 print('enter connection parameters:')37 host = input('\thost (leave empty for default localhost): ') or 'localhost'38 port = input('\tport (leave empty for default 3307): ') or 330739 user = input('\tuser (leave empty for default root): ') or 'root'40 password = getpass.getpass(f'\tpassword for {user}: ')41 update_config(host, port, user, password)42 db = pymysql.connect(host=host, port=port, user=user, password=password)43 print('creating schema and tables...')44 tock = time.time()45 execute_script('./inserts/create_tables.sql', db)46 tick = time.time()47 print(f'\tdone in {(tick-tock):.3f} sec')48 db = pymysql.connect(host=host, port=port, user=user, password=password, database='univ_db')49 print('inserting data...')50 tock = time.time()51 execute_script('./inserts/faculties.sql', db)52 execute_script('./inserts/chairs.sql', db)53 execute_script('./inserts/teachers.sql', db)54 execute_script('./inserts/groups.sql', db)55 execute_script('./inserts/students.sql', db)56 execute_script('./inserts/subjects.sql', db)57 execute_script('./inserts/schedule.sql', db)58 execute_script('./inserts/mega_session.sql', db)59 tick = time.time()60 print(f'\tdone in {(tick-tock):.3f} sec')61 print('creating stored procedures...')62 tock = time.time()63 for i in range(1, 14):64 execute_script(f'./queries/task_{i}.sql', db)65 tick = time.time()66 print(f'\tdone in {(tick-tock):.3f} sec')...
JavaScript.py
Source:JavaScript.py
1from selenium import webdriver2driver = webdriver.Chrome()3# Click4javaScript = "document.getElementsByName('username')[0].click();"5driver.execute_script(javaScript)6btn = driver.find_element_by_name ("spbutton")7driver.execute_script ("arguments[0].click();", btn)8# feel an element with dATA9driver.execute_script("document.getElementById('login_email').value='12345'")10javaScript = "document.getElementsByClassName('gsc-input')[0].value = 'T' "11driver.execute_script(javaScript)12driver.execute_script("arguments[0].value='Bhupi';", btn)13# you can have more than one JavaScript action in your statement.14userName = driver.find_element_by_xpath("//button[@name='username']")15password = driver.find_element_by_xpath("//button[@name='password']")16driver.execute_script("arguments[0].click();arguments[1].click();", userName, password)17# extract the value with Javascript Executor18print(driver.execute_script('return document.getElementsByName("username")[0].value'))19print(driver.execute_script('return document.getElementById("fsr").innerText'))20# to scroll with Javascript executor21driver.execute_script ("window.scrollTo(0,document.body.scrollHeight);")22# print the page title in console23print(driver.execute_script('return document.title'))24# print the page URL in console25print(driver.execute_script('return document.URL'))26# Check specific radio button or checkbox27driver.execute_script("document.querySelector(\"input[value='seven']\").checked=true")...
Using AI Code Generation
1 build();2driver.executeScript('window.alert("Hello World");');3driver.quit();4from selenium import webdriver5from selenium.webdriver.common.desired_capabilities import DesiredCapabilities6driver = webdriver.Remote(7driver.execute_script('window.alert("Hello World");')8driver.quit()9$capabilities = array(WebDriverCapabilityType::BROWSER_NAME => 'chrome');10$driver = RemoteWebDriver::create($host, $capabilities);11$driver->executeScript('window.alert("Hello World");');12$driver->quit();13 build();14driver.executeAsyncScript('window.setTimeout(arguments[arguments.length - 1], 5000);');15driver.quit();16from selenium import webdriver17from selenium.webdriver.common.desired_capabilities import DesiredCapabilities18driver = webdriver.Remote(19driver.execute_async_script('window.setTimeout(arguments[arguments.length - 1], 5000);')20driver.quit()
Using AI Code Generation
1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3var location = 'Dulles:Chrome';4var options = {5 videoParams: {6 }7};8client.runTest(url, options, function(err, data) {9 if (err) return console.error(err);10 console.log('Test status:', data.statusText);11 console.log('Test ID:', data.data.testId);12 console.log('Test URL:', data.data.userUrl);13 console.log('Test results:', data.data.summary);14 var testId = data.data.testId;15 client.getTestResults(testId, function(err, data) {16 if (err) return console.error(err);17 console.log('Test status:', data.statusText);18 console.log('Test ID:', data.data.testId);19 console.log('Test URL:', data.data.userUrl);20 console.log('Test results:', data.data.summary);21 });22});
Using AI Code Generation
1var wptdriver = require('wptdriver');2wptdriver.execute_script('test.js', function(err, result) {3 console.log(result);4});5var wptdriver = require('wptdriver');6wptdriver.execute_async_script('test.js', function(err, result) {7 console.log(result);8});9var wptdriver = require('wptdriver');10wptdriver.execute_async_script('test.js', function(err, result) {11 console.log(result);12});13var wptdriver = require('wptdriver');14 console.log(result);15});16var wptdriver = require('wptdriver');17wptdriver.get_current_url(function(err, result) {18 console.log(result);19});20var wptdriver = require('wptdriver');21wptdriver.get_title(function(err, result) {22 console.log(result);23});24var wptdriver = require('wptdriver');25wptdriver.get_window_handle(function(err, result) {26 console.log(result);27});28var wptdriver = require('wptdriver');29wptdriver.get_window_handles(function(err, result) {30 console.log(result);31});32var wptdriver = require('wptdriver');33wptdriver.get_window_size(function(err, result) {34 console.log(result);35});36var wptdriver = require('wptdriver');37wptdriver.go_back(function(err, result) {38 console.log(result);39});40var wptdriver = require('w
Using AI Code Generation
1wptb.execute_script("test.js", "test", "test");2### wptb.execute_script_sync()3wptb.execute_script_sync("test.js", "test", "test");4### wptb.wait_for()5wptb.wait_for(1000);6### wptb.wait_for_element()7wptb.wait_for_element("div#id");8### wptb.wait_for_element_not_present()9wptb.wait_for_element_not_present("div#id");10### wptb.wait_for_element_visible()11wptb.wait_for_element_visible("div#id");12### wptb.wait_for_element_not_visible()
Using AI Code Generation
1test('scroll to bottom', async t => {2 .execute_script('window.scrollTo(0, document.body.scrollHeight);')3 .wait(5000)4 .takeScreenshot()5})6test('scroll to bottom', async t => {7 .execute_script('window.scrollTo(0, document.body.scrollHeight);')8 .wait(5000)9 .takeScreenshot()10})11test('scroll to bottom', async t => {12 .execute_async_script('window.scrollTo(0, document.body.scrollHeight);')13 .wait(5000)14 .takeScreenshot()15})16test('scroll to bottom', async t => {17 .execute_async_script('window.scrollTo(0, document.body.scrollHeight);')18 .wait(5000)19 .takeScreenshot()20})21test('get page source', async t => {22 .get_page_source()23 .then(function (source) {24 console.log(source)25 })26})
Using AI Code Generation
1var wpt = require('./wptdriver.js');2var fs = require('fs');3var script = fs.readFileSync('test2.js');4var script2 = fs.readFileSync('test3.js');5wpt.execute_script(script.toString(), function(err, result) {6 if (err) {7 console.log(err);8 } else {9 console.log(result);10 }11});12wpt.execute_script(script2.toString(), function(err, result) {13 if (err) {14 console.log(err);15 } else {16 console.log(result);17 }18});19wpt.end();20wptdriver.execute_script('console.log("hello world");');21wptdriver.execute_script('console.log("hello world 2");');22var wpt = require('./wptdriver.js');23var fs = require('fs');24wpt.get_full_page_screenshot(function(err, result) {25 if (err) {26 console.log(err);27 } else {28 fs.writeFile('screenshot.png', result, 'base64', function(err) {29 if (err) {30 console.log(err);31 }32 });33 }34});35wpt.end();36var wpt = require('./wptdriver.js');37var fs = require('fs');38wpt.get_page_source(function(err, result) {39 if (err) {40 console.log(err);41 } else {42 fs.writeFile('source.html', result, 'utf8', function(err) {43 if (err) {44 console.log(err);45 }46 });47 }48});49wpt.end();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!