How to use prerender_remote method in wpt

Best JavaScript code snippet using wpt

utils.js

Source:utils.js Github

copy

Full Screen

1const STORE_URL = '/speculation-rules/prerender/resources/key-value-store.py';2function assertSpeculationRulesIsSupported() {3 assert_implements(4 'supports' in HTMLScriptElement,5 'HTMLScriptElement.supports is not supported');6 assert_implements(7 HTMLScriptElement.supports('speculationrules'),8 '<script type="speculationrules"> is not supported');9}10// Starts prerendering for `url`.11function startPrerendering(url) {12 // Adds <script type="speculationrules"> and specifies a prerender candidate13 // for the given URL.14 // TODO(https://crbug.com/1174978): <script type="speculationrules"> may not15 // start prerendering for some reason (e.g., resource limit). Implement a16 // WebDriver API to force prerendering.17 const script = document.createElement('script');18 script.type = 'speculationrules';19 script.text = `{"prerender": [{"source": "list", "urls": ["${url}"] }] }`;20 document.head.appendChild(script);21}22class PrerenderChannel extends EventTarget {23 #ids = new Set();24 #url;25 #active = true;26 constructor(name, uid = new URLSearchParams(location.search).get('uid')) {27 super();28 this.#url = `/speculation-rules/prerender/resources/deprecated-broadcast-channel.py?name=${name}&uid=${uid}`;29 (async() => {30 while (this.#active) {31 // Add the "keepalive" option to avoid fetch() results in unhandled32 // rejection with fetch abortion due to window.close().33 const messages = await (await fetch(this.#url, {keepalive: true})).json();34 for (const {data, id} of messages) {35 if (!this.#ids.has(id))36 this.dispatchEvent(new MessageEvent('message', {data}));37 this.#ids.add(id);38 }39 }40 })();41 }42 close() {43 this.#active = false;44 }45 set onmessage(m) {46 this.addEventListener('message', m)47 }48 async postMessage(data) {49 const id = new Date().valueOf();50 this.#ids.add(id);51 // Add the "keepalive" option to prevent messages from being lost due to52 // window.close().53 await fetch(this.#url, {method: 'POST', body: JSON.stringify({data, id}), keepalive: true});54 }55}56// Reads the value specified by `key` from the key-value store on the server.57async function readValueFromServer(key) {58 const serverUrl = `${STORE_URL}?key=${key}`;59 const response = await fetch(serverUrl);60 if (!response.ok)61 throw new Error('An error happened in the server');62 const value = await response.text();63 // The value is not stored in the server.64 if (value === "")65 return { status: false };66 return { status: true, value: value };67}68// Convenience wrapper around the above getter that will wait until a value is69// available on the server.70async function nextValueFromServer(key) {71 while (true) {72 // Fetches the test result from the server.73 const { status, value } = await readValueFromServer(key);74 if (!status) {75 // The test result has not been stored yet. Retry after a while.76 await new Promise(resolve => setTimeout(resolve, 100));77 continue;78 }79 return value;80 }81}82// Writes `value` for `key` in the key-value store on the server.83async function writeValueToServer(key, value) {84 const serverUrl = `${STORE_URL}?key=${key}&value=${value}`;85 await fetch(serverUrl);86}87// Loads the initiator page, and navigates to the prerendered page after it88// receives the 'readyToActivate' message.89function loadInitiatorPage() {90 // Used to communicate with the prerendering page.91 const prerenderChannel = new PrerenderChannel('prerender-channel');92 window.addEventListener('unload', () => {93 prerenderChannel.close();94 });95 // We need to wait for the 'readyToActivate' message before navigation96 // since the prerendering implementation in Chromium can only activate if the97 // response for the prerendering navigation has already been received and the98 // prerendering document was created.99 const readyToActivate = new Promise((resolve, reject) => {100 prerenderChannel.addEventListener('message', e => {101 if (e.data != 'readyToActivate')102 reject(`The initiator page receives an unsupported message: ${e.data}`);103 resolve(e.data);104 });105 });106 const url = new URL(document.URL);107 url.searchParams.append('prerendering', '');108 // Prerender a page that notifies the initiator page of the page's ready to be109 // activated via the 'readyToActivate'.110 startPrerendering(url.toString());111 // Navigate to the prerendered page after being informed.112 readyToActivate.then(() => {113 window.location = url.toString();114 }).catch(e => {115 const testChannel = new PrerenderChannel('test-channel');116 testChannel.postMessage(117 `Failed to navigate the prerendered page: ${e.toString()}`);118 testChannel.close();119 window.close();120 });121}122// Returns messages received from the given PrerenderChannel123// so that callers do not need to add their own event listeners.124// nextMessage() returns a promise which resolves with the next message.125//126// Usage:127// const channel = new PrerenderChannel('channel-name');128// const messageQueue = new BroadcastMessageQueue(channel);129// const message1 = await messageQueue.nextMessage();130// const message2 = await messageQueue.nextMessage();131// message1 and message2 are the messages received.132class BroadcastMessageQueue {133 constructor(c) {134 this.messages = [];135 this.resolveFunctions = [];136 this.channel = c;137 this.channel.addEventListener('message', e => {138 if (this.resolveFunctions.length > 0) {139 const fn = this.resolveFunctions.shift();140 fn(e.data);141 } else {142 this.messages.push(e.data);143 }144 });145 }146 // Returns a promise that resolves with the next message from this queue.147 nextMessage() {148 return new Promise(resolve => {149 if (this.messages.length > 0)150 resolve(this.messages.shift())151 else152 this.resolveFunctions.push(resolve);153 });154 }155}156// Returns <iframe> element upon load.157function createFrame(url) {158 return new Promise(resolve => {159 const frame = document.createElement('iframe');160 frame.src = url;161 frame.onload = () => resolve(frame);162 document.body.appendChild(frame);163 });164}165async function create_prerendered_page(t, opt = {}) {166 const baseUrl = '/speculation-rules/prerender/resources/exec.py';167 const init_uuid = token();168 const prerender_uuid = token();169 const discard_uuid = token();170 const init_remote = new RemoteContext(init_uuid);171 const prerender_remote = new RemoteContext(prerender_uuid);172 const discard_remote = new RemoteContext(discard_uuid);173 window.open(`${baseUrl}?uuid=${init_uuid}&init`, '_blank', 'noopener');174 const params = new URLSearchParams(baseUrl.search);175 params.set('uuid', prerender_uuid);176 params.set('discard_uuid', discard_uuid);177 for (const p in opt)178 params.set(p, opt[p]);179 const url = `${baseUrl}?${params.toString()}`;180 await init_remote.execute_script(url => {181 const a = document.createElement('a');182 a.href = url;183 a.innerText = 'Activate';184 document.body.appendChild(a);185 const rules = document.createElement('script');186 rules.type = "speculationrules";187 rules.text = JSON.stringify({prerender: [{source: 'list', urls: [url]}]});188 document.head.appendChild(rules);189 }, [url]);190 await Promise.any([191 prerender_remote.execute_script(() => {192 window.import_script_to_prerendered_page = src => {193 const script = document.createElement('script');194 script.src = src;195 document.head.appendChild(script);196 return new Promise(resolve => script.addEventListener('load', resolve));197 }198 }), new Promise(r => t.step_timeout(r, 3000))199 ]);200 t.add_cleanup(() => {201 init_remote.execute_script(() => window.close());202 discard_remote.execute_script(() => window.close());203 prerender_remote.execute_script(() => window.close());204 });205 async function tryToActivate() {206 const prerendering = prerender_remote.execute_script(() => new Promise(resolve => {207 if (!document.prerendering)208 resolve('activated');209 else document.addEventListener('prerenderingchange', () => resolve('activated'));210 }));211 const discarded = discard_remote.execute_script(() => Promise.resolve('discarded'));212 init_remote.execute_script(url => {213 location.href = url;214 }, [url]);215 return Promise.any([prerendering, discarded]);216 }217 async function activate() {218 const prerendering = await tryToActivate();219 if (prerendering !== 'activated')220 throw new Error('Should not be prerendering at this point')221 }222 return {223 exec: (fn, args) => prerender_remote.execute_script(fn, args),224 activate,225 tryToActivate226 };227}228function test_prerender_restricted(fn, expected, label) {229 promise_test(async t => {230 const {exec} = await create_prerendered_page(t);231 let result = null;232 try {233 await exec(fn);234 result = "OK";235 } catch (e) {236 result = e.name;237 }238 assert_equals(result, expected);239 }, label);240}241function test_prerender_defer(fn, label) {242 promise_test(async t => {243 const {exec, activate} = await create_prerendered_page(t);244 let activated = false;245 const deferred = exec(fn);246 const post = new Promise(resolve =>247 deferred.then(result => {248 assert_true(activated, "Deferred operation should occur only after activation");249 resolve(result);250 }));251 await activate();252 activated = true;253 await post;254 }, label);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const wpt = new WebPageTest('www.webpagetest.org');3 const data = await wpt.prerenderRemote({4 });5 console.log(data);6})();7(async () => {8 const wpt = new WebPageTest('www.webpagetest.org');9 const data = await wpt.prerender({10 });11 console.log(data);12})();13(async () => {14 const wpt = new WebPageTest('www.webpagetest.org');15 const data = await wpt.runTestRemote({16 });17 console.log(data);18})();19(async () => {20 const wpt = new WebPageTest('www.webpagetest.org');21 const data = await wpt.runTest({22 });23 console.log(data);24})();25(async () => {26 const wpt = new WebPageTest('www.webpagetest.org');27 const data = await wpt.runTestRemote({

Full Screen

Using AI Code Generation

copy

Full Screen

1var options = {2 wptOptions: {3 }4};5wpt.prerender_remote(options, function (err, data) {6 if (err) {7 console.log(err);8 } else {9 console.log(data);10 }11});12var options = {13 wptOptions: {14 }15};16wpt.runtest(options, function (err, data) {17 if (err) {18 console.log(err);19 } else {20 console.log(data);21 }22});23var options = {24};25wpt.testinfo(options, function (err, data) {26 if (err) {27 console.log(err);28 } else {29 console.log(data);30 }31});32wpt.getLocations(function (err, data) {33 if (err) {34 console.log(err);35 } else {36 console.log(data);37 }38});39wpt.getBrowsers(function (err, data) {40 if (err) {41 console.log(err);42 } else {43 console.log(data);44 }45});46wpt.getTesters(function (err, data) {47 if (err) {48 console.log(err);49 } else {50 console.log(data);51 }52});53var options = {54};55wpt.getTestStatus(options, function (err, data

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptdriver = require('wptdriver');2var options = {3};4wptdriver.get(url, options, function(err, data) {5 if (err) {6 console.log('Error: ' + err);7 } else {8 console.log(data);9 }10});11var options = {12}13var wptdriver = require('wptdriver');14var options = {15};16wptdriver.get(url, options, function(err, data) {17 if (err) {18 console.log('Error: ' + err);19 } else {20 console.log(data);21 }22});

Full Screen

Using AI Code Generation

copy

Full Screen

1var prerender_remote = require('node-wpt').prerender_remote;2}, function(data) {3 console.log(data);4}, function(error) {5 console.log(error);6});7var runtest = require('node-wpt').runtest;8}, function(data) {9 console.log(data);10}, function(error) {11 console.log(error);12});13var gettestinfo = require('node-wpt').gettestinfo;14gettestinfo('150624_1J_1a1a', {15}, function(data) {16 console.log(data);17}, function(error) {18 console.log(error);19});20var getteststatus = require('node-wpt').getteststatus;

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful