Best JavaScript code snippet using wpt
utils.sub.js
Source: utils.sub.js
1/**2 * Utilities for initiating prefetch via speculation rules.3 */4// Resolved URL to find this script.5const SR_PREFETCH_UTILS_URL = new URL(document.currentScript.src, document.baseURI);6// Hostname for cross origin urls.7const PREFETCH_PROXY_BYPASS_HOST = "{{hosts[alt][]}}";8class PrefetchAgent extends RemoteContext {9 constructor(uuid, t) {10 super(uuid);11 this.t = t;12 }13 getExecutorURL(options = {}) {14 let {hostname, username, password, protocol, executor, ...extra} = options;15 let params = new URLSearchParams({uuid: this.context_id, ...extra});16 if(executor === undefined) {17 executor = "executor.sub.html";18 }19 let url = new URL(`${executor}?${params}`, SR_PREFETCH_UTILS_URL);20 if(hostname !== undefined) {21 url.hostname = hostname;22 }23 if(username !== undefined) {24 url.username = username;25 }26 if(password !== undefined) {27 url.password = password;28 }29 if(protocol !== undefined) {30 url.protocol = protocol;31 url.port = protocol === "https" ? "{{ports[https][0]}}" : "{{ports[http][0]}}";32 }33 return url;34 }35 // Requests prefetch via speculation rules.36 //37 // In the future, this should also use browser hooks to force the prefetch to38 // occur despite heuristic matching, etc., and await the completion of the39 // prefetch.40 async forceSinglePrefetch(url, extra = {}) {41 await this.execute_script((url, extra) => {42 insertSpeculationRules({ prefetch: [{source: 'list', urls: [url], ...extra}] });43 }, [url, extra]);44 return new Promise(resolve => this.t.step_timeout(resolve, 2000));45 }46 async navigate(url) {47 await this.execute_script((url) => {48 window.executor.suspend(() => {49 location.href = url;50 });51 }, [url]);52 url.username = '';53 url.password = '';54 assert_equals(55 await this.execute_script(() => location.href),56 url.toString(),57 "expected navigation to reach destination URL");58 await this.execute_script(() => {});59 }60 async getRequestHeaders() {61 return this.execute_script(() => requestHeaders);62 }63 async getResponseCookies() {64 return this.execute_script(() => {65 let cookie = {};66 document.cookie.split(/\s*;\s*/).forEach((kv)=>{67 let [key, value] = kv.split(/\s*=\s*/);68 cookie[key] = value;69 });70 return cookie;71 });72 }73 async getRequestCookies() {74 return this.execute_script(() => window.requestCookies);75 }76 async getRequestCredentials() {77 return this.execute_script(() => window.requestCredentials);78 }79}80// Produces n URLs with unique UUIDs which will record when they are prefetched.81function getPrefetchUrlList(n) {82 let urls = [];83 for (let i=0; i<n; i++) {84 let params = new URLSearchParams({uuid: token()});85 urls.push(new URL(`prefetch.py?${params}`, SR_PREFETCH_UTILS_URL));86 }87 return urls;88}89function getRedirectUrl() {90 let params = new URLSearchParams({uuid: token()});91 return new URL(`redirect.py?${params}`, SR_PREFETCH_UTILS_URL);92}93async function isUrlPrefetched(url) {94 let response = await fetch(url, {redirect: 'follow'});95 assert_true(response.ok);96 return response.json();97}98// Must also include /common/utils.js and /common/dispatcher/dispatcher.js to use this.99async function spawnWindow(t, options = {}) {100 let agent = new PrefetchAgent(token(), t);101 let w = window.open(agent.getExecutorURL(options), options);102 t.add_cleanup(() => w.close());103 return agent;104}105function insertSpeculationRules(body) {106 let script = document.createElement('script');107 script.type = 'speculationrules';108 script.textContent = JSON.stringify(body);109 document.head.appendChild(script);110}111function assert_prefetched (requestHeaders, description) {112 assert_in_array(requestHeaders.purpose, ["", "prefetch"], "The vendor-specific header Purpose, if present, must be 'prefetch'.");113 assert_equals(requestHeaders.sec_purpose, "prefetch", description);114}115function assert_not_prefetched (requestHeaders, description){116 assert_equals(requestHeaders.purpose, "", description);117 assert_equals(requestHeaders.sec_purpose, "", description);...
Using AI Code Generation
1var url = wptb_utils.SR_PREFETCH_UTILS_URL;2var req = new XMLHttpRequest();3req.open("GET", url, true);4req.onload = function() {5 if (req.readyState == 4 && req.status == 200) {6 var resp = JSON.parse(req.responseText);7 console.log(resp);8 }9};10req.send(null);
Using AI Code Generation
1var callback = function(response) {2};3wptb_prefetch_utils.SR_PREFETCH_UTILS_URL(url, callback);4wptb_prefetch_utils.SR_PREFETCH_UTILS_URL(url);5wptb_prefetch_utils.SR_PREFETCH_UTILS_URL(url, null, "GET");6var headers = {"Content-Type":"application/json"};7wptb_prefetch_utils.SR_PREFETCH_UTILS_URL(url, null, "GET", headers);8var body = {"key":"value"};9wptb_prefetch_utils.SR_PREFETCH_UTILS_URL(url, null, "POST", headers, body);
Check out the latest blogs from LambdaTest on this topic:
Testing is a critical step in any web application development process. However, it can be an overwhelming task if you don’t have the right tools and expertise. A large percentage of websites still launch with errors that frustrate users and negatively affect the overall success of the site. When a website faces failure after launch, it costs time and money to fix.
We launched LT Browser in 2020, and we were overwhelmed by the response as it was awarded as the #5 product of the day on the ProductHunt platform. Today, after 74,585 downloads and 7,000 total test runs with an average of 100 test runs each day, the LT Browser has continued to help developers build responsive web designs in a jiffy.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!