How to use promiseDocumentReady method in wpt

Best JavaScript code snippet using wpt

ExtensionContent.jsm

Source:ExtensionContent.jsm Github

copy

Full Screen

...208 }209 async injectInto(window) {210 let context = this.extension.getContext(window);211 if (this.runAt === "document_end") {212 await promiseDocumentReady(window.document);213 } else if (this.runAt === "document_idle") {214 let readyThenIdle = promiseDocumentReady(window.document).then(() => {215 return new Promise(resolve =>216 window.requestIdleCallback(resolve, {timeout: idleTimeout}));217 });218 await Promise.race([219 readyThenIdle,220 promiseDocumentLoaded(window.document),221 ]);222 }223 return this.inject(context);224 }225 /**226 * Tries to inject this script into the given window and sandbox, if227 * there are pending operations for the window's current load state.228 *229 * @param {BaseContext} context230 * The content script context into which to inject the scripts.231 * @returns {Promise<any>}232 * Resolves to the last value in the evaluated script, when233 * execution is complete.234 */235 async inject(context) {236 DocumentManager.lazyInit();237 if (this.requiresCleanup) {238 context.addScript(this);239 }240 let cssPromise;241 if (this.cssURLs.length) {242 let window = context.contentWindow;243 let winUtils = getWinUtils(window);244 let type = this.cssOrigin === "user" ? winUtils.USER_SHEET : winUtils.AUTHOR_SHEET;245 if (this.removeCSS) {246 for (let url of this.cssURLs) {247 this.cssCache.deleteDocument(url, window.document);248 runSafeSyncWithoutClone(winUtils.removeSheetUsingURIString, url, type);249 }250 } else {251 cssPromise = Promise.all(this.loadCSS()).then(sheets => {252 let window = context.contentWindow;253 if (!window) {254 return;255 }256 for (let {url, sheet} of sheets) {257 this.cssCache.addDocument(url, window.document);258 runSafeSyncWithoutClone(winUtils.addSheet, sheet, type);259 }260 });261 }262 }263 let scriptPromises = this.compileScripts();264 let scripts = scriptPromises.map(promise => promise.script);265 // If not all scripts are already available in the cache, block266 // parsing and wait all promises to resolve.267 if (!scripts.every(script => script)) {268 let promise = Promise.all(scriptPromises);269 // If we're supposed to inject at the start of the document load,270 // and we haven't already missed that point, block further parsing271 // until the scripts have been loaded.272 let {document} = context.contentWindow;273 if (this.runAt === "document_start" && document.readyState !== "complete") {274 document.blockParsing(promise, {blockScriptCreated: false});275 }276 scripts = await promise;277 }278 let result;279 // The evaluations below may throw, in which case the promise will be280 // automatically rejected.281 TelemetryStopwatch.start(CONTENT_SCRIPT_INJECTION_HISTOGRAM, context);282 try {283 for (let script of scripts) {284 result = script.executeInGlobal(context.cloneScope);285 }286 if (this.matcher.jsCode) {287 result = Cu.evalInSandbox(this.matcher.jsCode, context.cloneScope, "latest");288 }289 } finally {290 TelemetryStopwatch.finish(CONTENT_SCRIPT_INJECTION_HISTOGRAM, context);291 }292 await cssPromise;293 return result;294 }295}296defineLazyGetter(Script.prototype, "cssURLs", function() {297 // We can handle CSS urls (css) and CSS code (cssCode).298 let urls = this.css.slice();299 if (this.matcher.cssCode) {300 urls.push("data:text/css;charset=utf-8," + encodeURIComponent(this.matcher.cssCode));301 }302 return urls;303});304/**305 * An execution context for semi-privileged extension content scripts.306 *307 * This is the child side of the ContentScriptContextParent class308 * defined in ExtensionParent.jsm.309 */310class ContentScriptContextChild extends BaseContext {311 constructor(extension, contentWindow) {312 super("content_child", extension);313 this.setContentWindow(contentWindow);314 let frameId = WebNavigationFrames.getFrameId(contentWindow);315 this.frameId = frameId;316 this.scripts = [];317 let contentPrincipal = contentWindow.document.nodePrincipal;318 let ssm = Services.scriptSecurityManager;319 // Copy origin attributes from the content window origin attributes to320 // preserve the user context id.321 let attrs = contentPrincipal.originAttributes;322 let extensionPrincipal = ssm.createCodebasePrincipal(this.extension.baseURI, attrs);323 this.isExtensionPage = contentPrincipal.equals(extensionPrincipal);324 let principal;325 if (ssm.isSystemPrincipal(contentPrincipal)) {326 // Make sure we don't hand out the system principal by accident.327 // also make sure that the null principal has the right origin attributes328 principal = ssm.createNullPrincipal(attrs);329 } else if (this.isExtensionPage) {330 principal = contentPrincipal;331 } else {332 principal = [contentPrincipal, extensionPrincipal];333 }334 if (this.isExtensionPage) {335 // This is an iframe with content script API enabled and its principal336 // should be the contentWindow itself. We create a sandbox with the337 // contentWindow as principal and with X-rays disabled because it338 // enables us to create the APIs object in this sandbox object and then339 // copying it into the iframe's window. See bug 1214658.340 this.sandbox = Cu.Sandbox(contentWindow, {341 sandboxPrototype: contentWindow,342 sameZoneAs: contentWindow,343 wantXrays: false,344 isWebExtensionContentScript: true,345 });346 } else {347 // This metadata is required by the Developer Tools, in order for348 // the content script to be associated with both the extension and349 // the tab holding the content page.350 let metadata = {351 "inner-window-id": this.innerWindowID,352 addonId: extensionPrincipal.addonId,353 };354 this.sandbox = Cu.Sandbox(principal, {355 metadata,356 sandboxPrototype: contentWindow,357 sameZoneAs: contentWindow,358 wantXrays: true,359 isWebExtensionContentScript: true,360 wantExportHelpers: true,361 wantGlobalProperties: ["XMLHttpRequest", "fetch"],362 originAttributes: attrs,363 });364 Cu.evalInSandbox(`365 window.JSON = JSON;366 window.XMLHttpRequest = XMLHttpRequest;367 window.fetch = fetch;368 `, this.sandbox);369 }370 Object.defineProperty(this, "principal", {371 value: Cu.getObjectPrincipal(this.sandbox),372 enumerable: true,373 configurable: true,374 });375 this.url = contentWindow.location.href;376 defineLazyGetter(this, "chromeObj", () => {377 let chromeObj = Cu.createObjectIn(this.sandbox);378 Schemas.inject(chromeObj, this.childManager);379 return chromeObj;380 });381 Schemas.exportLazyGetter(this.sandbox, "browser", () => this.chromeObj);382 Schemas.exportLazyGetter(this.sandbox, "chrome", () => this.chromeObj);383 }384 injectAPI() {385 if (!this.isExtensionPage) {386 throw new Error("Cannot inject extension API into non-extension window");387 }388 // This is an iframe with content script API enabled (bug 1214658)389 Schemas.exportLazyGetter(this.contentWindow,390 "browser", () => this.chromeObj);391 Schemas.exportLazyGetter(this.contentWindow,392 "chrome", () => this.chromeObj);393 }394 get cloneScope() {395 return this.sandbox;396 }397 addScript(script) {398 if (script.requiresCleanup) {399 this.scripts.push(script);400 }401 }402 close() {403 super.unload();404 if (this.contentWindow) {405 for (let script of this.scripts) {406 script.cleanup(this.contentWindow);407 }408 // Overwrite the content script APIs with an empty object if the APIs objects are still409 // defined in the content window (bug 1214658).410 if (this.isExtensionPage) {411 Cu.createObjectIn(this.contentWindow, {defineAs: "browser"});412 Cu.createObjectIn(this.contentWindow, {defineAs: "chrome"});413 }414 }415 Cu.nukeSandbox(this.sandbox);416 this.sandbox = null;417 }418}419defineLazyGetter(ContentScriptContextChild.prototype, "messenger", function() {420 // The |sender| parameter is passed directly to the extension.421 let sender = {id: this.extension.id, frameId: this.frameId, url: this.url};422 let filter = {extensionId: this.extension.id};423 let optionalFilter = {frameId: this.frameId};424 return new Messenger(this, [this.messageManager], sender, filter, optionalFilter);425});426defineLazyGetter(ContentScriptContextChild.prototype, "childManager", function() {427 apiManager.lazyInit();428 let localApis = {};429 let can = new CanOfAPIs(this, apiManager, localApis);430 let childManager = new ChildAPIManager(this, this.messageManager, can, {431 envType: "content_parent",432 url: this.url,433 });434 this.callOnClose(childManager);435 return childManager;436});437// Responsible for creating ExtensionContexts and injecting content438// scripts into them when new documents are created.439DocumentManager = {440 // Map[windowId -> Map[ExtensionChild -> ContentScriptContextChild]]441 contexts: new Map(),442 initialized: false,443 lazyInit() {444 if (this.initialized) {445 return;446 }447 this.initialized = true;448 Services.obs.addObserver(this, "inner-window-destroyed");449 Services.obs.addObserver(this, "memory-pressure");450 },451 uninit() {452 Services.obs.removeObserver(this, "inner-window-destroyed");453 Services.obs.removeObserver(this, "memory-pressure");454 },455 observers: {456 "inner-window-destroyed"(subject, topic, data) {457 let windowId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;458 MessageChannel.abortResponses({innerWindowID: windowId});459 // Close any existent content-script context for the destroyed window.460 if (this.contexts.has(windowId)) {461 let extensions = this.contexts.get(windowId);462 for (let context of extensions.values()) {463 context.close();464 }465 this.contexts.delete(windowId);466 }467 },468 "memory-pressure"(subject, topic, data) {469 let timeout = data === "heap-minimize" ? 0 : undefined;470 for (let cache of ChromeUtils.nondeterministicGetWeakSetKeys(scriptCaches)) {471 cache.clear(timeout);472 }473 },474 },475 observe(subject, topic, data) {476 this.observers[topic].call(this, subject, topic, data);477 },478 shutdownExtension(extension) {479 for (let extensions of this.contexts.values()) {480 let context = extensions.get(extension);481 if (context) {482 context.close();483 extensions.delete(extension);484 }485 }486 },487 getContexts(window) {488 let winId = getInnerWindowID(window);489 let extensions = this.contexts.get(winId);490 if (!extensions) {491 extensions = new Map();492 this.contexts.set(winId, extensions);493 }494 return extensions;495 },496 // For test use only.497 getContext(extensionId, window) {498 for (let [extension, context] of this.getContexts(window)) {499 if (extension.id === extensionId) {500 return context;501 }502 }503 },504 getContentScriptGlobals(window) {505 let extensions = this.contexts.get(getInnerWindowID(window));506 if (extensions) {507 return Array.from(extensions.values(), ctx => ctx.sandbox);508 }509 return [];510 },511 initExtensionContext(extension, window) {512 extension.getContext(window).injectAPI();513 },514};515this.ExtensionContent = {516 BrowserExtensionContent,517 Script,518 shutdownExtension(extension) {519 DocumentManager.shutdownExtension(extension);520 },521 // This helper is exported to be integrated in the devtools RDP actors,522 // that can use it to retrieve the existent WebExtensions ContentScripts523 // of a target window and be able to show the ContentScripts source in the524 // DevTools Debugger panel.525 getContentScriptGlobals(window) {526 return DocumentManager.getContentScriptGlobals(window);527 },528 initExtensionContext(extension, window) {529 DocumentManager.initExtensionContext(extension, window);530 },531 getContext(extension, window) {532 let extensions = DocumentManager.getContexts(window);533 let context = extensions.get(extension);534 if (!context) {535 context = new ContentScriptContextChild(extension, window);536 extensions.set(extension, context);537 }538 return context;539 },540 handleExtensionCapture(global, width, height, options) {541 let win = global.content;542 const XHTML_NS = "http://www.w3.org/1999/xhtml";543 let canvas = win.document.createElementNS(XHTML_NS, "canvas");544 canvas.width = width;545 canvas.height = height;546 canvas.mozOpaque = true;547 let ctx = canvas.getContext("2d");548 // We need to scale the image to the visible size of the browser,549 // in order for the result to appear as the user sees it when550 // settings like full zoom come into play.551 ctx.scale(canvas.width / win.innerWidth, canvas.height / win.innerHeight);552 ctx.drawWindow(win, win.scrollX, win.scrollY, win.innerWidth, win.innerHeight, "#fff");553 return canvas.toDataURL(`image/${options.format}`, options.quality / 100);554 },555 handleDetectLanguage(global, target) {556 let doc = target.content.document;557 return promiseDocumentReady(doc).then(() => {558 let elem = doc.documentElement;559 let language = (elem.getAttribute("xml:lang") || elem.getAttribute("lang") ||560 doc.contentLanguage || null);561 // We only want the last element of the TLD here.562 // Only country codes have any effect on the results, but other563 // values cause no harm.564 let tld = doc.location.hostname.match(/[a-z]*$/)[0];565 // The CLD2 library used by the language detector is capable of566 // analyzing raw HTML. Unfortunately, that takes much more memory,567 // and since it's hosted by emscripten, and therefore can't shrink568 // its heap after it's grown, it has a performance cost.569 // So we send plain text instead.570 let encoder = new DocumentEncoder(doc, "text/plain", Ci.nsIDocumentEncoder.SkipInvisibleContent);571 let text = encoder.encodeToStringWithMaxLength(60 * 1024);...

Full Screen

Full Screen

ExtensionUtils.jsm

Source:ExtensionUtils.jsm Github

copy

Full Screen

...135 *136 * @param {Document} doc The document to await the load of.137 * @returns {Promise<Document>}138 */139function promiseDocumentReady(doc) {140 if (doc.readyState == "interactive" || doc.readyState == "complete") {141 return Promise.resolve(doc);142 }143 return new Promise(resolve => {144 doc.addEventListener(145 "DOMContentLoaded",146 function onReady(event) {147 if (event.target === event.currentTarget) {148 doc.removeEventListener("DOMContentLoaded", onReady, true);149 resolve(doc);150 }151 },152 true153 );...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var rp = require('request-promise');3var cheerio = require('cheerio');4var fs = require('fs');5var data = [];6function getWikiData() {7 return new Promise(function(resolve, reject) {8 wptools.page(url).get().then(function(page) {9 var infobox = page.infobox;10 var table = page.tables;11 var infoboxes = [];12 var tables = [];13 for (var key in infobox) {14 if (infobox.hasOwnProperty(key)) {15 var info = {};16 info['key'] = key;17 info['value'] = infobox[key];18 infoboxes.push(info);19 }20 }21 for (var i = 0; i < table.length; i++) {22 var tableData = table[i].data;23 for (var j = 0; j < tableData.length; j++) {24 var tableRow = tableData[j];25 var city = {};26 for (var k = 0; k < tableRow.length; k++) {27 var row = tableRow[k];28 var key = row.key;29 var value = row.value;30 if (key) {31 city[key] = value;32 }33 }34 tables.push(city);35 }36 }37 resolve({38 });39 }).catch(function(err) {40 reject(err);41 });42 });43}44function getWikiDataUsingRequest() {45 return new Promise(function(resolve, reject) {46 rp(url).then(function(html) {47 var $ = cheerio.load(html);48 var infobox = $('.infobox');49 var infoboxes = [];50 var tables = [];51 infobox.find('tr').each(function(i, tr) {52 var info = {};53 var key = $(tr).find('th').text();54 var value = $(tr).find('td').text();55 info['key'] = key;56 info['value'] = value;57 infoboxes.push(info);58 });59 var table = $('table.wikitable');60 table.find('tr').each(function(i, tr) {61 var city = {};62 $(tr

Full Screen

Using AI Code Generation

copy

Full Screen

1function testPromiseDocumentReady() {2 promiseDocumentReady().then(function() {3 console.log('Document is ready.');4 });5}6function testPromiseElementReady() {7 promiseElementReady('p').then(function() {8 console.log('Paragraph is ready.');9 });10}

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var Promise = require('bluebird');3var fs = Promise.promisifyAll(require('fs'));4var page = wptools.page('Barack_Obama');5page.get().then(function(data) {6 fs.writeFileAsync('data.json', JSON.stringify(data));7});8var wptools = require('wptools');9var Promise = require('bluebird');10var fs = Promise.promisifyAll(require('fs'));11var page = wptools.page('Barack_Obama');12page.get().then(function(data) {13 fs.writeFileAsync('data.json', JSON.stringify(data));14});15var wptools = require('wptools');16var Promise = require('bluebird');17var fs = Promise.promisifyAll(require('fs'));18var page = wptools.page('Barack_Obama');19page.get().then(function(data) {20 fs.writeFileAsync('data.json', JSON.stringify(data));21});22var wptools = require('wptools');23var Promise = require('bluebird');24var fs = Promise.promisifyAll(require('fs'));25var page = wptools.page('Barack_Obama');26page.get().then(function(data) {27 fs.writeFileAsync('data.json', JSON.stringify(data));28});29var wptools = require('wptools');30var Promise = require('bluebird');31var fs = Promise.promisifyAll(require('fs'));32var page = wptools.page('Barack_Obama');33page.get().then(function(data) {34 fs.writeFileAsync('data.json', JSON.stringify(data));35});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2let getWikiPage = (wikiPage) => {3 return wptools.promiseDocumentReady(wikiPage);4}5module.exports = {6}7const { getWikiPage } = require('./test');8getWikiPage('javascript').then((doc) => {9 console.log(doc);10});11const { getWikiPage } = require('./test');12getWikiPage('javascript').then((doc) => {13 console.log(doc);14});15const { getWikiPage } = require('./test');

Full Screen

Using AI Code Generation

copy

Full Screen

1wpt.promiseDocumentReady().then(function() {2 var myVar = setInterval(function(){ myTimer() }, 1000);3 var timeleft = 5;4 var d = new Date();5 var n = d.getTime();6 var d1 = new Date();7 var n1 = d1.getTime();8 function myTimer() {9 var d1 = new Date();10 var n1 = d1.getTime();11 if (timeleft == 0) {12 clearInterval(myVar);13 var d = new Date();14 var n = d.getTime();15 var time = n-n1;16 wpt.logData('time', time);17 } else {18 timeleft--;19 }20 }21});

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