How to use prerenderChannel 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}22// Reads the value specified by `key` from the key-value store on the server.23async function readValueFromServer(key) {24 const serverUrl = `${STORE_URL}?key=${key}`;25 const response = await fetch(serverUrl);26 if (!response.ok)27 throw new Error('An error happened in the server');28 const value = await response.text();29 // The value is not stored in the server.30 if (value === "")31 return { status: false };32 return { status: true, value: value };33}34// Convenience wrapper around the above getter that will wait until a value is35// available on the server.36async function nextValueFromServer(key) {37 while (true) {38 // Fetches the test result from the server.39 const { status, value } = await readValueFromServer(key);40 if (!status) {41 // The test result has not been stored yet. Retry after a while.42 await new Promise(resolve => setTimeout(resolve, 100));43 continue;44 }45 return value;46 }47}48// Writes `value` for `key` in the key-value store on the server.49async function writeValueToServer(key, value) {50 const serverUrl = `${STORE_URL}?key=${key}&value=${value}`;51 await fetch(serverUrl);52}53// Loads the initiator page, and navigates to the prerendered page after it54// receives the 'readyToActivate' message.55function loadInitiatorPage() {56 // Used to communicate with the prerendering page.57 const prerenderChannel = new BroadcastChannel('prerender-channel');58 window.addEventListener('unload', () => {59 prerenderChannel.close();60 });61 // We need to wait for the 'readyToActivate' message before navigation62 // since the prerendering implementation in Chromium can only activate if the63 // response for the prerendering navigation has already been received and the64 // prerendering document was created.65 const readyToActivate = new Promise((resolve, reject) => {66 prerenderChannel.addEventListener('message', e => {67 if (e.data != 'readyToActivate')68 reject(`The initiator page receives an unsupported message: ${e.data}`);69 resolve(e.data);70 });71 });72 const url = new URL(document.URL);73 url.searchParams.append('prerendering', '');74 // Prerender a page that notifies the initiator page of the page's ready to be75 // activated via the 'readyToActivate'.76 startPrerendering(url.toString());77 // Navigate to the prerendered page after being informed.78 readyToActivate.then(() => {79 window.location = url.toString();80 }).catch(e => {81 const testChannel = new BroadcastChannel('test-channel');82 testChannel.postMessage(83 `Failed to navigate the prerendered page: ${e.toString()}`);84 testChannel.close();85 window.close();86 });87}88// Returns messages received from the given BroadcastChannel89// so that callers do not need to add their own event listeners.90// nextMessage() returns a promise which resolves with the next message.91//92// Usage:93// const channel = new BroadcastChannel('channel-name');94// const messageQueue = new BroadcastMessageQueue(channel);95// const message1 = await messageQueue.nextMessage();96// const message2 = await messageQueue.nextMessage();97// message1 and message2 are the messages received.98class BroadcastMessageQueue {99 constructor(broadcastChannel) {100 this.messages = [];101 this.resolveFunctions = [];102 this.channel = broadcastChannel;103 this.channel.addEventListener('message', e => {104 if (this.resolveFunctions.length > 0) {105 const fn = this.resolveFunctions.shift();106 fn(e.data);107 } else {108 this.messages.push(e.data);109 }110 });111 }112 // Returns a promise that resolves with the next message from this queue.113 nextMessage() {114 return new Promise(resolve => {115 if (this.messages.length > 0)116 resolve(this.messages.shift())117 else118 this.resolveFunctions.push(resolve);119 });120 }121}122// Returns <iframe> element upon load.123function createFrame(url) {124 return new Promise(resolve => {125 const frame = document.createElement('iframe');126 frame.src = url;127 frame.onload = () => resolve(frame);128 document.body.appendChild(frame);129 });130}131class PrerenderChannel extends EventTarget {132 broadcastChannel = null;133 constructor(uid, name) {134 super();135 this.broadcastChannel = new BroadcastChannel(`${uid}-${name}`);136 this.broadcastChannel.addEventListener('message', e => {137 this.dispatchEvent(new CustomEvent('message', {detail: e.data}));138 });139 }140 postMessage(message) {141 this.broadcastChannel.postMessage(message);142 }143 close() {144 this.broadcastChannel.close();145 }146};147async function create_prerendered_page(t) {148 const uuid = token();149 new PrerenderChannel(uuid, 'log').addEventListener('message', message => {150 // Calling it with ['log'] to avoid lint issue. This log should be used for debugging151 // the prerendered context, not testing.152 if(window.console)153 console['log']('[From Prerendered]', ...message.detail);154 });155 const execChannel = new PrerenderChannel(uuid, 'exec');156 const initChannel = new PrerenderChannel(uuid, 'initiator');157 const exec = (func, args = []) => {158 const receiver = token();159 execChannel.postMessage({receiver, fn: func.toString(), args});160 return new Promise((resolve, reject) => {161 const channel = new PrerenderChannel(uuid, receiver);162 channel.addEventListener('message', ({detail}) => {163 channel.close();164 if (detail.error)165 reject(detail.error)166 else167 resolve(detail.result);168 });169 })170 };171 window.open(`/speculation-rules/prerender/resources/eval-init.html?uuid=${uuid}`, '_blank', 'noopener');172 t.add_cleanup(() => initChannel.postMessage('close'));173 t.add_cleanup(() => exec(() => window.close()));174 await new Promise(resolve => {175 const channel = new PrerenderChannel(uuid, 'ready');176 channel.addEventListener('message', () => {177 channel.close();178 resolve();179 });180 });181 async function activate() {182 const prerendering = exec(() => new Promise(resolve =>183 document.addEventListener('prerenderingchange', () => {184 resolve(document.prerendering);185 })));186 initChannel.postMessage('activate');187 if (await prerendering)188 throw new Error('Should not be prerendering at this point')189 }190 return {191 exec,192 activate193 };194}195function test_prerender_restricted(fn, expected, label) {196 promise_test(async t => {197 const {exec} = await create_prerendered_page(t);198 let result = null;199 try {200 await exec(fn);201 result = "OK";202 } catch (e) {203 result = e.name;204 }205 assert_equals(result, expected);206 }, label);207}208function test_prerender_defer(fn, label) {209 promise_test(async t => {210 const {exec, activate} = await create_prerendered_page(t);211 let activated = false;212 const deferred = exec(fn);213 const post = new Promise(resolve =>214 deferred.then(result => {215 assert_true(activated, "Deferred operation should occur only after activation");216 resolve(result);217 }));218 await new Promise(resolve => t.step_timeout(resolve, 100));219 await activate();220 activated = true;221 await post;222 }, label);...

Full Screen

Full Screen

deferred-promise-utils.js

Source:deferred-promise-utils.js Github

copy

Full Screen

1/**2 * This file co-works with a html file and utils.js to test a promise that3 * should be deferred during prerendering.4 *5 * Usage example:6 * Suppose the html is "prerender-promise-test.html"7 * On prerendering page, prerender-promise-test.html?prerendering:8 * const prerenderEventCollector = new PrerenderEventCollector();9 * const promise = {a promise that should be deferred during prerendering};10 * prerenderEventCollector.start(promise, {promise name});11 *12 * On the initiator page, prerender-promise-test.html:13 * execute14 * `loadInitiatorPage();`15 */16// Collects events that happen relevant to a prerendering page.17// An event is added when:18// 1. start() is called.19// 2. a prerenderingchange event is dispatched on this document.20// 3. the promise passed to start() is resolved.21// 4. addEvent() is called manually.22class PrerenderEventCollector {23 constructor() {24 this.eventsSeen_ = [];25 }26 // Adds an event to `eventsSeen_` along with the prerendering state of the27 // page.28 addEvent(eventMessage) {29 this.eventsSeen_.push(30 {event: eventMessage, prerendering: document.prerendering});31 }32 // Starts collecting events until the promise resolves. Triggers activation by33 // telling the initiator page that it is ready for activation.34 async start(promise, promiseName) {35 assert_true(document.prerendering);36 this.addEvent(`started waiting ${promiseName}`);37 promise38 .then(39 () => {40 this.addEvent(`finished waiting ${promiseName}`);41 },42 (error) => {43 if (error instanceof Error)44 error = error.name;45 this.addEvent(`${promiseName} rejected: ${error}`);46 })47 .finally(() => {48 // Used to communicate with the main test page.49 const testChannel = new BroadcastChannel('test-channel');50 // Send the observed events back to the main test page.51 testChannel.postMessage(this.eventsSeen_);52 testChannel.close();53 window.close();54 });55 document.addEventListener('prerenderingchange', () => {56 this.addEvent('prerendering change');57 });58 // Post a task to give the implementation a chance to fail in case it59 // resolves a promise without waiting for activation.60 setTimeout(() => {61 // Used to communicate with the initiator page.62 const prerenderChannel = new BroadcastChannel('prerender-channel');63 // Inform the initiator page that this page is ready to be activated.64 prerenderChannel.postMessage('readyToActivate');65 prerenderChannel.close();66 }, 0);67 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var api = new wpt('www.webpagetest.org');3var options = {4};5api.prerenderChannel(options, function(err, data) {6 if (err) {7 console.log(err);8 } else {9 console.log(data);10 }11});12{ statusCode: 200,13 { statusCode: 200,14 { statusCode: 200,

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) console.error(err);4 else console.log(data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8 if (err) console.error(err);9 else console.log(data);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13wpt.getLocations(function(err, data) {14 if (err) console.error(err);15 else console.log(data);16});17var wpt = require('webpagetest');18var wpt = new WebPageTest('www.webpagetest.org');19wpt.getTesters(function(err, data) {20 if (err) console.error(err);21 else console.log(data);22});23var wpt = require('webpagetest');24var wpt = new WebPageTest('www.webpagetest.org');25wpt.getBrowsers(function(err, data) {26 if (err) console.error(err);27 else console.log(data);28});29var wpt = require('webpagetest');30var wpt = new WebPageTest('www.webpagetest.org');31wpt.getTesters(function(err, data) {32 if (err) console.error(err);33 else console.log(data);34});35var wpt = require('webpagetest');36var wpt = new WebPageTest('www.webpagetest.org');37wpt.getTesters(function(err, data) {38 if (err) console.error(err);39 else console.log(data);40});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = { host: 'www.webpagetest.org', key: 'A.12345678901234567890123456789012', timeout: 10000 };3var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');4wpt.prerenderChannel(url, function(err, data) {5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptdriver = require('wptdriver');2var driver = new wptdriver.WptDriver();3 if (err) {4 console.log('Error: ', err);5 } else {6 console.log('Result: ', res);7 }8});

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