Best JavaScript code snippet using wpt
generic-sensor-iframe-tests.sub.js
Source:generic-sensor-iframe-tests.sub.js
1async function send_message_to_iframe(iframe, message, reply) {2 if (reply === undefined) {3 reply = 'success';4 }5 return new Promise((resolve, reject) => {6 let messageHandler = e => {7 if (e.data.command !== message.command) {8 return;9 }10 window.removeEventListener('message', messageHandler);11 if (e.data.result === reply) {12 resolve();13 } else {14 reject();15 }16 }17 window.addEventListener('message', messageHandler);18 iframe.contentWindow.postMessage(message, '*');19 });20}21function run_generic_sensor_iframe_tests(sensorName) {22 const sensorType = self[sensorName];23 const featurePolicies = get_feature_policies_for_sensor(sensorName);24 sensor_test(async t => {25 assert_true(sensorName in self);26 const iframe = document.createElement('iframe');27 iframe.allow = featurePolicies.join(';') + ';';28 iframe.src = 'https://{{domains[www1]}}:{{ports[https][0]}}/generic-sensor/resources/iframe_sensor_handler.html';29 // Create sensor inside cross-origin nested browsing context.30 const iframeLoadWatcher = new EventWatcher(t, iframe, 'load');31 document.body.appendChild(iframe);32 await iframeLoadWatcher.wait_for('load');33 await send_message_to_iframe(iframe, {command: 'create_sensor',34 type: sensorName});35 // Focus on the main frame and test that sensor receives readings.36 window.focus();37 const sensor = new sensorType();38 const sensorWatcher = new EventWatcher(t, sensor, ['reading', 'error']);39 sensor.start();40 await sensorWatcher.wait_for('reading');41 const cachedTimeStamp = sensor.timestamp;42 // Focus on the cross-origin frame and verify that sensor reading updates in43 // the top level browsing context are suspended.44 iframe.contentWindow.focus();45 await send_message_to_iframe(iframe, {command: 'start_sensor'});46 assert_equals(cachedTimeStamp, sensor.timestamp);47 // Focus on the main frame, verify that sensor reading updates are resumed.48 window.focus();49 await sensorWatcher.wait_for('reading');50 assert_greater_than(sensor.timestamp, cachedTimeStamp);51 sensor.stop();52 // Verify that sensor in cross-origin frame is suspended.53 await send_message_to_iframe(iframe, {command: 'is_sensor_suspended'}, true);54 await send_message_to_iframe(iframe, {command: 'reset_sensor_backend'});55 // Remove iframe from main document.56 iframe.parentNode.removeChild(iframe);57 }, `${sensorName}: sensor is suspended and resumed when focus traverses from\58 to cross-origin frame`);59 sensor_test(async t => {60 assert_true(sensorName in self);61 const iframe = document.createElement('iframe');62 iframe.allow = featurePolicies.join(';') + ';';63 iframe.src = 'https://{{host}}:{{ports[https][0]}}/generic-sensor/resources/iframe_sensor_handler.html';64 // Create sensor inside same-origin nested browsing context.65 const iframeLoadWatcher = new EventWatcher(t, iframe, 'load');66 document.body.appendChild(iframe);67 await iframeLoadWatcher.wait_for('load');68 await send_message_to_iframe(iframe, {command: 'create_sensor',69 type: sensorName});70 // Focus on main frame and test that sensor receives readings.71 window.focus();72 const sensor = new sensorType({73 // generic_sensor_mocks.js uses a default frequency of 5Hz for sensors.74 // We deliberately use a higher frequency here to make it easier to spot75 // spurious, unexpected 'reading' events caused by the main frame's76 // sensor not stopping early enough.77 // TODO(rakuco): Create a constant with the 5Hz default frequency instead78 // of using magic numbers.79 frequency: 1580 });81 const sensorWatcher = new EventWatcher(t, sensor, ['reading', 'error']);82 sensor.start();83 await sensorWatcher.wait_for('reading');84 let cachedTimeStamp = sensor.timestamp;85 // Stop sensor in main frame, so that sensorWatcher would not receive86 // readings while sensor in iframe is started. Sensors that are active and87 // belong to the same-origin context are not suspended automatically when88 // focus changes to another same-origin iframe, so if we do not explicitly89 // stop them we may receive extra 'reading' events that cause the test to90 // fail (see e.g. https://crbug.com/857520).91 sensor.stop();92 iframe.contentWindow.focus();93 await send_message_to_iframe(iframe, {command: 'start_sensor'});94 // Start sensor on main frame, verify that readings are updated.95 window.focus();96 sensor.start();97 await sensorWatcher.wait_for('reading');98 assert_greater_than(sensor.timestamp, cachedTimeStamp);99 cachedTimeStamp = sensor.timestamp;100 sensor.stop();101 // Verify that sensor in nested browsing context is not suspended.102 await send_message_to_iframe(iframe, {command: 'is_sensor_suspended'}, false);103 // Verify that sensor in top level browsing context is receiving readings.104 iframe.contentWindow.focus();105 sensor.start();106 await sensorWatcher.wait_for('reading');107 assert_greater_than(sensor.timestamp, cachedTimeStamp);108 sensor.stop();109 await send_message_to_iframe(iframe, {command: 'reset_sensor_backend'});110 // Remove iframe from main document.111 iframe.parentNode.removeChild(iframe);112 }, `${sensorName}: sensor is not suspended when focus traverses from\113 to same-origin frame`);114 sensor_test(async t => {115 assert_true(sensorName in self);116 const iframe = document.createElement('iframe');117 iframe.allow = featurePolicies.join(';') + ';';118 iframe.src = 'https://{{host}}:{{ports[https][0]}}/generic-sensor/resources/iframe_sensor_handler.html';119 // Create sensor in the iframe (we do not care whether this is a120 // cross-origin nested context in this test).121 const iframeLoadWatcher = new EventWatcher(t, iframe, 'load');122 document.body.appendChild(iframe);123 await iframeLoadWatcher.wait_for('load');124 await send_message_to_iframe(iframe, {command: 'create_sensor',125 type: sensorName});126 iframe.contentWindow.focus();127 await send_message_to_iframe(iframe, {command: 'start_sensor'});128 // Remove iframe from main document and change focus. When focus changes,129 // we need to determine whether a sensor must have its execution suspended130 // or resumed (section 4.2.3, "Focused Area" of the Generic Sensor API131 // spec). In Blink, this involves querying a frame, which might no longer132 // exist at the time of the check.133 // Note that we cannot send the "reset_sensor_backend" command because the134 // iframe is discarded with the removeChild call.135 iframe.parentNode.removeChild(iframe);136 window.focus();137 }, `${sensorName}: losing a document's frame with an active sensor does not crash`);...
background.js
Source:background.js
1chrome.runtime.onInstalled.addListener(({reason}) => {2 if (reason === chrome.runtime.OnInstalledReason.INSTALL) {3 chrome.storage.local.set({config: getDefaultConfig()})4 }5})6class WebRequestManager {7 attached = false 8 constructor() {9 chrome.storage.local.get("config", ({config = getDefaultConfig()}) => {10 this.config = config11 this.handleConfigChange()12 })13 chrome.storage.onChanged.addListener((changes, area) => {14 if (area !== "local") return 15 const newConfig = changes.config?.newValue16 if (!newConfig) return 17 this.config = newConfig18 this.handleConfigChange()19 })20 }21 release = () => {22 chrome.webRequest.onHeadersReceived.removeListener(this.handleHeadersReceived)23 }24 handleHeadersReceived = (details) => {25 let newHeaders = []26 let featurePolicies = []27 details.responseHeaders.forEach(header => {28 if (header.name.trim().toLowerCase() !== "feature-policy") {29 newHeaders.push({name: header.name, value: header.value, binaryValue: header.binaryValue})30 } else {31 featurePolicies = [...featurePolicies, ...fpParser(header.value.trim())]32 }33 })34 let flag = false 35 this.rules.filter(v => v.enabled).forEach(rule => {36 if (rule.triggerType === "STARTS_WITH") {37 if (!details.url.startsWith(rule.url)) return 38 } else if (rule.triggerType === "REGEX") {39 if (!rule.regex.test(details.url)) return 40 }41 let ogCount = featurePolicies.length42 featurePolicies = featurePolicies.filter(fp => fp.feature !== rule.feature)43 if (rule.type === "CLEAR") {44 if (featurePolicies.length < ogCount) {45 flag = true 46 }47 } else {48 flag = true 49 featurePolicies.push({feature: rule.feature, allowList: [rule.allowList || "'none'"]})50 }51 })52 if (!flag) return 53 if (featurePolicies.length > 0) {54 newHeaders.push({55 name: "feature-policy",56 value: featurePolicies.map(f => [f.feature, ...f.allowList].join(" ")).join(";")57 })58 }59 return {responseHeaders: newHeaders}60 }61 attach = () => {62 if (this.attached) return 63 this.attached = true 64 chrome.webRequest.onHeadersReceived.addListener(this.handleHeadersReceived, {65 urls: ["https://*/*", "http://*/*"],66 types: ['main_frame']67 }, ['blocking', 'responseHeaders'])68 }69 detach = () => {70 if (!this.attached) return 71 chrome.webRequest.onHeadersReceived.removeListener(this.handleHeadersReceived)72 this.attached = false 73 }74 handleConfigChange = () => {75 chrome.browserAction.setIcon({path: this.config.enabled ? {"128": "icon128.png"} : {"128": "icon128_grayscale.png"}})76 this.rules = this.config.rules.map(rule => ({77 ...rule,78 regex: rule.triggerType === "REGEX" ? new RegExp(rule.url, "i") : null 79 }))80 if (this.config.enabled && this.config.rules.filter(v => v.enabled).length) {81 this.attach()82 } else {83 this.detach()84 }85 }86}87function fpParser(value) {88 value = value.trim() 89 if (value.length === 0) return []90 return value.split(";").map(v => {91 let [feature, ...allowList] = v.trim().split(/\s+/)92 return {feature, allowList}93 })94}...
Using AI Code Generation
1const { test } = require('tap')2const { featurePolicies } = require('wpt')3test('featurePolicies', async t => {4 const policies = await featurePolicies()5 t.ok(policies)6 t.ok(policies.length > 0)7})8ok 1 (unnamed assert)9ok 2 (unnamed assert)10not ok 1 (unnamed assert)11 at: processTicksAndRejections (internal/process/task_queues.js:93:5)12not ok 1 (unnamed assert)13 at: processTicksAndRejections (internal/process/task_queues.js:93:5)14not ok 1 (unnamed assert)15 at: processTicksAndRejections (internal/process/task_queues.js:93:5)16not ok 1 (unnamed assert)17 at: processTicksAndRejections (internal/process/task_queues.js:93:5)18not ok 1 (unnamed assert)
Using AI Code Generation
1var featurePolicies = require("featurePolicies");2var featurePolicies = require("featurePolicies");3var featurePolicies = require("featurePolicies");4var featurePolicies = require("featurePolicies");5var featurePolicies = require("featurePolicies");6var featurePolicies = require("featurePolicies");7var featurePolicies = require("featurePolicies");8var featurePolicies = require("featurePolicies");9var featurePolicies = require("featurePolicies");10var featurePolicies = require("featurePolicies");11var featurePolicies = require("featurePolicies");12var featurePolicies = require("featurePolicies");13featurePolicies.setFeaturePolicies("payment", ["self",
Using AI Code Generation
1import { featurePolicies } from 'wpt';2featurePolicies({feature: 'vibrate', value: 'none'});3import { featurePolicies } from 'wpt';4featurePolicies({feature: 'vibrate', value: 'none'});5import { featurePolicies } from 'wpt';6featurePolicies({feature: 'vibrate', value: 'none'});7import { featurePolicies } from 'wpt';8featurePolicies({feature: 'vibrate', value: 'none'});9import { featurePolicies } from 'wpt';10featurePolicies({feature: 'vibrate', value: 'none'});11import { featurePolicies } from 'wpt';12featurePolicies({feature: 'vibrate', value: 'none'});13import { featurePolicies } from 'wpt';14featurePolicies({feature: 'vibrate', value: 'none'});15import { featurePolicies } from 'wpt';16featurePolicies({feature: 'vibrate', value: 'none'});17import { featurePolicies } from 'wpt';18featurePolicies({feature: 'vibrate', value: 'none'});
Using AI Code Generation
1const { featurePolicies } = require('wpt');2(async () => {3 const result = await featurePolicies({ policy: 'accelerometer', feature: 'accelerometer' });4 console.log(result);5 const result1 = await featurePolicies({ policy: 'accelerometer', feature: 'accelerometer', iframe: true });6 console.log(result1);7 const result2 = await featurePolicies({ policy: 'accelerometer', feature: 'accelerometer', nestedIframes: true });8 console.log(result2);9 const result3 = await featurePolicies({ policy: 'accelerometer', feature: 'accelerometer', nestedIframes: true, sameOriginIframe: true });10 console.log(result3);11 const result4 = await featurePolicies({ policy: 'accelerometer', feature: 'accelerometer', nestedIframes: true, crossOriginIframe: true });12 console.log(result4);13 const result5 = await featurePolicies({ policy: 'accelerometer', feature: 'accelerometer', nestedIframes: true, crossOriginIframe: true, sameOriginIframe: true });14 console.log(result5);15})();
Using AI Code Generation
1function run_test() {2 var server = createServer();3 server.registerPathHandler("/featurePolicies", featurePoliciesHandler);4 server.start(-1);5 var chan = makeChan(server);6 chan.asyncOpen2(new ChannelListener(checkFeaturePolicies, null));7 do_test_pending();8}9function checkFeaturePolicies(request, data, ctx) {10 do_check_eq(request.status, Components.results.NS_OK);11 var featurePolicies = request.getResponseHeader("Feature-Policies");12 do_check_eq(featurePolicies, "geolocation *; midi *; notifications *; push *; sync-xhr *; microphone *; camera *; magnetometer *; gyroscope *; speaker *; vibrate *; fullscreen *; payment *");13 do_test_finished();14}15function featurePoliciesHandler(metadata, response) {16 response.setHeader("Feature-Policies", featurePolicies([{name: "geolocation", value: "*", allow: true}, {name: "midi", value: "*", allow: true}, {name: "notifications", value: "*", allow: true}, {name: "push", value: "*", allow: true}, {name: "sync-xhr", value: "*", allow: true}, {name: "microphone", value: "*", allow: true}, {name: "camera", value: "*", allow: true}, {name: "magnetometer", value: "*", allow: true}, {name: "gyroscope", value: "*", allow: true}, {name: "speaker", value: "*", allow: true}, {name: "vibrate", value: "*", allow
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!!