Best JavaScript code snippet using playwright-internal
commands.js
Source:commands.js
1// Copyright 2012 Selenium committers2// Copyright 2012 Software Freedom Conservancy3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15/**16 * @fileoverview Command handlers used by the SafariDriver's injected script.17 */18goog.provide('safaridriver.inject.commands');19goog.require('bot');20goog.require('bot.Error');21goog.require('bot.ErrorCode');22goog.require('bot.action');23goog.require('bot.dom');24goog.require('bot.frame');25goog.require('bot.inject');26goog.require('bot.inject.cache');27goog.require('bot.locators');28goog.require('bot.window');29goog.require('goog.array');30goog.require('goog.debug.Logger');31goog.require('goog.math.Coordinate');32goog.require('goog.math.Size');33goog.require('goog.net.cookies');34goog.require('goog.style');35goog.require('safaridriver.inject.CommandRegistry');36goog.require('safaridriver.inject.message.Activate');37goog.require('webdriver.atoms.element');38/**39 * @private {!goog.debug.Logger}40 * @const41 */42safaridriver.inject.commands.LOG_ = goog.debug.Logger.getLogger(43 'safaridriver.inject.commands');44/** @return {string} The name of the current window. */45safaridriver.inject.commands.getWindowName = function() {46 return window.name;47};48/** @return {string} The current URL. */49safaridriver.inject.commands.getCurrentUrl = function() {50 return window.location.href;51};52/**53 * Loads a new URL in the current page.54 * @param {!safaridriver.Command} command The command object.55 */56safaridriver.inject.commands.loadUrl = function(command) {57 window.location.href = /** @type {string} */ (command.getParameter('url'));58 // No need to send a response. The global page should be listening for the59 // navigate event.60};61/** Reloads the current page. */62safaridriver.inject.commands.reloadPage = function() {63 window.location.reload();64 // No need to send a response. The global page should be listening for the65 // navigate event.66};67/**68 * Stub that reports an error that navigating through the browser history does69 * not work for the SafariDriver.70 */71safaridriver.inject.commands.unsupportedHistoryNavigation = function() {72 throw Error('Yikes! Safari history navigation does not work. We can ' +73 'go forward or back, but once we do, we can no longer ' +74 'communicate with the page...');75};76/** @return {string} The document title. */77safaridriver.inject.commands.getTitle = function() {78 return document.title;79};80/** @return {string} A string representation of the current page source. */81safaridriver.inject.commands.getPageSource = function() {82 return new XMLSerializer().serializeToString(document);83};84/**85 * Defines an element locating command.86 * @param {function(!Object, (Document|Element)=):87 * (Element|!goog.array.ArrayLike.<Element>)} locatorFn The locator function88 * that should be used.89 * @return {function(!safaridriver.Command): !bot.response.ResponseObject} The90 * locator command function.91 * @private92 */93safaridriver.inject.commands.findElementCommand_ = function(locatorFn) {94 return function(command) {95 var locator = {};96 locator[command.getParameter('using')] = command.getParameter('value');97 var args = [locator];98 if (command.getParameter('id')) {99 args.push({'ELEMENT': command.getParameter('id')});100 }101 return bot.inject.executeScript(locatorFn, args);102 };103};104/**105 * Locates an element on the page.106 * @param {!safaridriver.Command} command The command object.107 * @return {!bot.response.ResponseObject} The command response.108 */109safaridriver.inject.commands.findElement =110 safaridriver.inject.commands.findElementCommand_(bot.locators.findElement);111/**112 * Locates multiple elements on the page.113 * @param {!safaridriver.Command} command The command object.114 * @return {bot.response.ResponseObject} The command response.115 */116safaridriver.inject.commands.findElements =117 safaridriver.inject.commands.findElementCommand_(bot.locators.findElements);118/**119 * Retrieves the element that currently has focus.120 * @return {!bot.response.ResponseObject} The response object.121 */122safaridriver.inject.commands.getActiveElement = function() {123 var getActiveElement = goog.partial(bot.dom.getActiveElement, document);124 return /** @type {!bot.response.ResponseObject} */ (bot.inject.executeScript(125 getActiveElement, []));126};127/**128 * Adds a new cookie to the page.129 * @param {!safaridriver.Command} command The command object.130 */131safaridriver.inject.commands.addCookie = function(command) {132 var cookie = command.getParameter('cookie');133 // The WebDriver wire protocol defines cookie expiration times in seconds134 // since midnight, January 1, 1970 UTC, but goog.net.Cookies expects them135 // to be in seconds since "right now".136 var maxAge = cookie['expiry'];137 if (goog.isNumber(maxAge)) {138 maxAge = new Date(maxAge - goog.now());139 }140 // TODO: check whether cookie['domain'] is valid.141 goog.net.cookies.set(cookie['name'], cookie['value'], maxAge,142 cookie['path'], cookie['domain'], cookie['secure']);143};144/**145 * @return {!Array.<{name:string, value:string}>} A list of the cookies visible146 * to the current page.147 */148safaridriver.inject.commands.getCookies = function() {149 var keys = goog.net.cookies.getKeys();150 return goog.array.map(keys, function(key) {151 return {152 'name': key,153 'value': goog.net.cookies.get(key)154 };155 });156};157/** Deletes all cookies visible to the current page. */158safaridriver.inject.commands.deleteCookies = function() {159 goog.net.cookies.clear();160};161/**162 * Deletes a specified cookie.163 * @param {!safaridriver.Command} command The command object.164 */165safaridriver.inject.commands.deleteCookie = function(command) {166 goog.net.cookies.remove(/** @type {string} */ (command.getParameter('name')));167};168/**169 * Creates a command that targets a specific DOM element.170 * @param {!Function} handlerFn The actual handler function. The first parameter171 * should be the Element to target.172 * @param {...string} var_args Any named parameters which should be extracted173 * and passed as arguments to {@code commandFn}.174 * @return {function(!safaridriver.Command)} The new element command function.175 * @private176 */177safaridriver.inject.commands.elementCommand_ = function(handlerFn, var_args) {178 var keys = goog.array.slice(arguments, 1);179 return function(command) {180 command = safaridriver.inject.commands.util.prepareElementCommand(command);181 var element = command.getParameter('id');182 var args = goog.array.concat(element, goog.array.map(keys, function(key) {183 return command.getParameter(key);184 }));185 return bot.inject.executeScript(handlerFn, args);186 };187};188/**189 * @param {!safaridriver.Command} command The command to execute.190 * @see bot.action.clear191 */192safaridriver.inject.commands.clearElement =193 safaridriver.inject.commands.elementCommand_(bot.action.clear);194/**195 * @param {!safaridriver.Command} command The command to execute.196 * @see bot.action.click197 */198safaridriver.inject.commands.clickElement =199 safaridriver.inject.commands.elementCommand_(bot.action.click);200/**201 * @param {!safaridriver.Command} command The command to execute.202 * @see bot.action.submit203 */204safaridriver.inject.commands.submitElement =205 safaridriver.inject.commands.elementCommand_(bot.action.submit);206/**207 * @param {!safaridriver.Command} command The command to execute.208 * @see webdriver.atoms.element.getAttribute209 */210safaridriver.inject.commands.getElementAttribute =211 safaridriver.inject.commands.elementCommand_(212 webdriver.atoms.element.getAttribute, 'name');213/**214 * @param {!safaridriver.Command} command The command to execute.215 * @see goog.style.getPageOffset216 */217safaridriver.inject.commands.getElementLocation =218 safaridriver.inject.commands.elementCommand_(goog.style.getPageOffset);219/**220 * @param {!safaridriver.Command} command The command to execute.221 * @see webdriver.atoms.element.getLocationInView222 */223safaridriver.inject.commands.getLocationInView =224 safaridriver.inject.commands.elementCommand_(225 webdriver.atoms.element.getLocationInView);226/**227 * @param {!safaridriver.Command} command The command to execute.228 * @see goog.style.getSize229 */230safaridriver.inject.commands.getElementSize =231 safaridriver.inject.commands.elementCommand_(goog.style.getSize);232/**233 * @param {!safaridriver.Command} command The command to execute.234 * @see webdriver.atoms.element.getText235 */236safaridriver.inject.commands.getElementText =237 safaridriver.inject.commands.elementCommand_(238 webdriver.atoms.element.getText);239/**240 * @param {!safaridriver.Command} command The command to execute.241 */242safaridriver.inject.commands.getElementTagName =243 safaridriver.inject.commands.elementCommand_(function(el) {244 return el.tagName.toLowerCase();245 });246/**247 * @param {!safaridriver.Command} command The command to execute.248 * @see bot.dom.isShown249 */250safaridriver.inject.commands.isElementDisplayed =251 safaridriver.inject.commands.elementCommand_(bot.dom.isShown);252/**253 * @param {!safaridriver.Command} command The command to execute.254 * @see bot.dom.isEnabled255 */256safaridriver.inject.commands.isElementEnabled =257 safaridriver.inject.commands.elementCommand_(bot.dom.isEnabled);258/**259 * @param {!safaridriver.Command} command The command to execute.260 * @see webdriver.atoms.element.isSelected261 */262safaridriver.inject.commands.isElementSelected =263 safaridriver.inject.commands.elementCommand_(264 webdriver.atoms.element.isSelected);265/**266 * @param {!safaridriver.Command} command The command to execute.267 */268safaridriver.inject.commands.elementEquals =269 safaridriver.inject.commands.elementCommand_(function(a, b) {270 return a === b;271 }, 'other');272/**273 * @param {!safaridriver.Command} command The command to execute.274 * @see bot.dom.getEffectiveStyle275 */276safaridriver.inject.commands.getCssValue =277 safaridriver.inject.commands.elementCommand_(bot.dom.getEffectiveStyle,278 'propertyName');279/**280 * @return {!goog.math.Coordinate} The position of the window.281 * @see bot.window.getPosition282 */283safaridriver.inject.commands.getWindowPosition = function() {284 return bot.window.getPosition();285};286/**287 * @param {!safaridriver.Command} command The command to execute.288 * @see bot.window.setPosition289 */290safaridriver.inject.commands.setWindowPosition = function(command) {291 var position = new goog.math.Coordinate(292 /** @type {number} */ (command.getParameter('x')),293 /** @type {number} */ (command.getParameter('y')));294 bot.window.setPosition(position);295};296/**297 * @return {!goog.math.Size} The size of the window.298 * @see bot.window.getSize299 */300safaridriver.inject.commands.getWindowSize = function() {301 return bot.window.getSize();302};303/**304 * @param {!safaridriver.Command} command The command to execute.305 * @see bot.window.setSize306 */307safaridriver.inject.commands.setWindowSize = function(command) {308 var size = new goog.math.Size(309 /** @type {number} */ (command.getParameter('width')),310 /** @type {number} */ (command.getParameter('height')));311 bot.window.setSize(size);312};313/** Maximizes the window. */314safaridriver.inject.commands.maximizeWindow = function() {315 window.moveTo(0, 0);316 window.resizeTo(window.screen.width, window.screen.height);317};318/**319 * Executes a command in the context of the current page.320 * @param {!safaridriver.Command} command The command to execute.321 * @param {!safaridriver.inject.Tab} tab A reference to the tab issuing this322 * command.323 * @return {!webdriver.promise.Promise} A promise that will be resolved with the324 * {@link bot.response.ResponseObject} from the page.325 * @throws {Error} If there is an error while sending the command to the page.326 */327safaridriver.inject.commands.executeInPage = function(command, tab) {328 command = safaridriver.inject.commands.util.prepareElementCommand(command);329 return tab.executeInPage(command);330};331/**332 * Locates a frame and sends a message to it to activate itself with the333 * extension. The located frame will be334 * @param {!safaridriver.Command} command The command to execute.335 * the target of all subsequent commands.336 * @throws {Error} If there is an error whilst locating the frame.337 */338safaridriver.inject.commands.switchToFrame = function(command) {339 var id = command.getParameter('id');340 var frameWindow;341 if (goog.isNull(id)) {342 safaridriver.inject.commands.LOG_.info('Resetting focus to window.top');343 frameWindow = window.top;344 } else if (goog.isString(id)) {345 safaridriver.inject.commands.LOG_.info(346 'Switching to frame by name or ID: ' + id);347 frameWindow = bot.frame.findFrameByNameOrId(/** @type {string} */ (id));348 } else if (goog.isNumber(id)) {349 safaridriver.inject.commands.LOG_.info(350 'Switching to frame by index: ' + id);351 frameWindow = bot.frame.findFrameByIndex(/** @type {number} */ (id));352 } else {353 var elementKey = /** @type {string} */ (id[bot.inject.ELEMENT_KEY]);354 safaridriver.inject.commands.LOG_.info('Switching to frame by ' +355 'WebElement: ' + elementKey);356 // ID must be a WebElement. Pull it from the cache.357 var frameElement = bot.inject.cache.getElement(elementKey);358 frameWindow = bot.frame.getFrameWindow(359 /** @type {!(HTMLIFrameElement|HTMLFrameElement)} */ (frameElement));360 }361 if (!frameWindow) {362 throw new bot.Error(bot.ErrorCode.NO_SUCH_FRAME,363 'Unable to locate frame with ' + id);364 }365 // De-activate ourselves. We should no longer respond to commands until366 // we are re-activated.367 safaridriver.inject.Tab.getInstance().setActive(false);368 var message = new safaridriver.inject.message.Activate(command);369 message.send(frameWindow);370};371goog.scope(function() {372var CommandName = webdriver.CommandName;373var commands = safaridriver.inject.commands;374// Commands that should be defined for every frame.375safaridriver.inject.CommandRegistry.getInstance()376 .defineModule(safaridriver.inject.commands.module.ID, goog.object.create(377 CommandName.ADD_COOKIE, commands.addCookie,378 CommandName.CLEAR_ELEMENT, commands.clearElement,379 CommandName.CLICK_ELEMENT, commands.clickElement,380 CommandName.DELETE_ALL_COOKIES, commands.deleteCookies,381 CommandName.DELETE_COOKIE, commands.deleteCookie,382 CommandName.ELEMENT_EQUALS, commands.elementEquals,383 CommandName.FIND_CHILD_ELEMENT, commands.findElement,384 CommandName.FIND_CHILD_ELEMENTS, commands.findElements,385 CommandName.FIND_ELEMENT, commands.findElement,386 CommandName.FIND_ELEMENTS, commands.findElements,387 CommandName.GET, commands.loadUrl,388 CommandName.GET_ACTIVE_ELEMENT, commands.getActiveElement,389 CommandName.GET_ALL_COOKIES, commands.getCookies,390 CommandName.GET_CURRENT_URL, commands.getCurrentUrl,391 CommandName.GET_ELEMENT_ATTRIBUTE, commands.getElementAttribute,392 CommandName.GET_ELEMENT_LOCATION, commands.getElementLocation,393 CommandName.GET_ELEMENT_LOCATION_IN_VIEW, commands.getLocationInView,394 CommandName.GET_ELEMENT_SIZE, commands.getElementSize,395 CommandName.GET_ELEMENT_TAG_NAME, commands.getElementTagName,396 CommandName.GET_ELEMENT_TEXT, commands.getElementText,397 CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, commands.getCssValue,398 CommandName.GET_PAGE_SOURCE, commands.getPageSource,399 CommandName.GET_TITLE, commands.getTitle,400 CommandName.GET_WINDOW_POSITION, commands.getWindowPosition,401 CommandName.GET_WINDOW_SIZE, commands.getWindowSize,402 CommandName.GO_BACK, commands.unsupportedHistoryNavigation,403 CommandName.GO_FORWARD, commands.unsupportedHistoryNavigation,404 CommandName.IS_ELEMENT_DISPLAYED, commands.isElementDisplayed,405 CommandName.IS_ELEMENT_ENABLED, commands.isElementEnabled,406 CommandName.IS_ELEMENT_SELECTED, commands.isElementSelected,407 CommandName.MAXIMIZE_WINDOW, commands.maximizeWindow,408 CommandName.REFRESH, commands.reloadPage,409 CommandName.SET_WINDOW_POSITION, commands.setWindowPosition,410 CommandName.SET_WINDOW_SIZE, commands.setWindowSize,411 CommandName.SUBMIT_ELEMENT, commands.submitElement,412 CommandName.SWITCH_TO_FRAME, commands.switchToFrame,413 // The extension handles window switches. It sends the command to this414 // injected script only as a means of retrieving the window name.415 CommandName.SWITCH_TO_WINDOW, commands.getWindowName));...
test_basic.js
Source:test_basic.js
1runTests([2 // Test 13 function() {4 var lastSVG = null;5 var sequenceNum = 0;6 var sequence = ['afterLoad', 'beforeInject', 'afterInject', 'beforeInject', 'afterInject', 'beforeInject', 'afterInject'];7 var testSequence = function(eventName) {8 if (sequenceNum === sequence.length || sequence[sequenceNum++] !== eventName) {9 fail();10 } else if (sequenceNum === sequence.length) {11 success();12 }13 };14 SVGInject.create('SVGInject1', {15 beforeInject: function(img, svg) {16 testSequence('beforeInject');17 if (lastSVG === svg) {18 fail();19 } else if (svg.parentNode && svg.parentNode.tagName == 'div') {20 fail();21 } else if (!img.parentNode) {22 fail();23 }24 lastSVG = svg;25 },26 afterInject: function(img, svg) {27 testSequence('afterInject');28 if (lastSVG !== svg) {29 fail();30 } else if (!svg.parentNode) {31 fail();32 } else if (img.parentNode) {33 fail();34 }35 },36 afterLoad: function(svg) {37 testSequence('afterLoad');38 }39 });40 },41 // Test 242 function() {43 var sequenceNum = 0;44 var sequence = [];45 for (var i = 0; i < 9; ++i) {46 sequence.push('beforeInject');47 sequence.push('afterInject');48 }49 var testSequence = function(eventName) {50 if (sequenceNum === sequence.length || sequence[sequenceNum++] !== eventName) {51 fail();52 } else if (sequenceNum === sequence.length) {53 success();54 }55 };56 SVGInject.create('SVGInject2', {57 beforeInject: function(img, svg) {58 testSequence('beforeInject');59 },60 afterInject: function(img, svg) {61 testSequence('afterInject');62 }63 });64 },65 // Test 366 function() {67 var includeAttributes = {68 'id': 'test_3_id',69 'class': 'inject-success',70 'data-test': 'test'71 };72 var notIncludeAttributes = ['src', 'onload', 'onerror', 'alt', 'title'];73 SVGInject.create('SVGInject3', {74 afterInject: function(img, svg) {75 for (var key in includeAttributes) {76 var val = includeAttributes[key];77 if (!svg.hasAttribute(key) || svg.getAttribute(key) !== val) {78 fail();79 return;80 }81 }82 for (var i = 0; i < notIncludeAttributes.length; ++i) {83 var notIncludeAttribute = notIncludeAttributes[i];84 if (svg.hasAttribute(notIncludeAttribute)) {85 fail();86 return;87 }88 }89 if (svg.firstElementChild.textContent !== 'businesspeople') {90 fail();91 return;92 }93 success();94 }95 });96 },97 // Test 498 function() {99 var notIncludeAttributes = ['id', 'data-test', 'onload', 'onerror', 'alt', 'title'];100 SVGInject.create('SVGInject4', {101 copyAttributes: false,102 beforeInject: function(img, svg) {103 svg.setAttribute('class', img.getAttribute('class'));104 },105 afterInject: function(img, svg) {106 for (var i = 0; i < notIncludeAttributes.length; ++i) {107 var notIncludeAttribute = notIncludeAttributes[i];108 if (svg.hasAttribute(notIncludeAttribute)) {109 fail();110 return;111 }112 if (svg.firstChild.tagName == 'title') {113 fail();114 return;115 }116 }117 success();118 }119 });120 },121 // Test 5122 function() {123 SVGInject.create('SVGInject5');124 var sequenceNum = 0;125 var sequence = [];126 for (var i = 0; i < 9; ++i) {127 if (i % 3 == 0) {128 sequence.push('afterLoad');129 }130 sequence.push('beforeInject');131 sequence.push('afterInject');132 }133 var testSequence = function(eventName) {134 if (sequenceNum === sequence.length || sequence[sequenceNum++] !== eventName) {135 fail();136 } else if (sequenceNum === sequence.length) {137 success();138 }139 };140 SVGInject5.setOptions({141 afterLoad: function(svg) {142 testSequence('afterLoad')143 },144 beforeInject: function(img, svg) {145 testSequence('beforeInject');146 },147 afterInject: function(img, svg) {148 testSequence('afterInject');149 }150 });151 domReady(function(event) {152 SVGInject5(document.getElementsByClassName('test-5'));153 });154 },155 // Test 6156 function() {157 var count = 0;158 SVGInject.create('SVGInject6', {159 afterLoad: failCallback(),160 beforeInject: failCallback(),161 afterInject: failCallback(),162 onFail: function(img) {163 img.src = 'imgs/test1.png';164 if (++count == 7) {165 success();166 } else if (count > 7) {167 fail();168 }169 }170 });171 },172 // Test 7173 function() {174 var count = 0;175 SVGInject.create('SVGInject7', {176 afterLoad: failCallback(),177 beforeInject: failCallback(),178 afterInject: failCallback(),179 onFail: function(img) {180 img.src = 'imgs/test1.png';181 if (++count == 7) {182 success();183 } else if (count > 7) {184 fail();185 }186 }187 });188 domReady(function(event) {189 SVGInject7(document.getElementsByClassName('test-7'));190 });191 },192 // Test 8193 function() {194 var count = 0;195 SVGInject.create('SVGInject8', {196 afterLoad: failCallback(),197 beforeInject: failCallback(),198 afterInject: failCallback(),199 onFail: function(img) {200 if (img.hasAttribute('onload')) {201 fail();202 }203 if (++count == 12) {204 success();205 } else if (count > 12) {206 fail();207 }208 }209 });210 domReady(function(event) {211 SVGInject8(document.getElementsByClassName('test-8'));212 });213 },214 // Test 9215 function() {216 var count = 0;217 SVGInject.create('SVGInject9');218 SVGInject9.setOptions({219 afterInject: function(img, svg) {220 // do not use className for SVGs!221 svg.setAttribute('class', 'inject-success');222 if (++count == 2) {223 success();224 } else if (count > 2) {225 fail();226 }227 }228 });229 domReady(function() {230 SVGInject9(document.getElementById('test-9').querySelectorAll('img[src$=".svg"]'));231 });232 },233 // Test 10234 function() {235 var sequenceNum = 0;236 var sequence = [];237 var svgs = [];238 for (var i = 0; i < 8; ++i) {239 sequence.push('afterLoad');240 sequence.push('beforeInject');241 sequence.push('afterInject');242 }243 var testSequence = function(eventName) {244 if (sequenceNum === sequence.length || sequence[sequenceNum++] !== eventName) {245 fail();246 } else if (sequenceNum === sequence.length) {247 success();248 }249 };250 SVGInject.create('SVGInject10', {251 useCache: false,252 beforeInject: function(img, svg) {253 testSequence('beforeInject');254 },255 afterInject: function(img, svg) {256 testSequence('afterInject');257 },258 afterLoad: function(svg) {259 if (svgs.indexOf(svg) !== -1) {260 fail();261 } else {262 svgs.push(svg);263 }264 testSequence('afterLoad');265 }266 });267 domReady(function() {268 SVGInject10(document.getElementsByClassName('test-10'));269 });270 },271 // Test 11272 function() {273 SVGInject.create('SVGInject11', {274 afterInject: function(img, svg) {275 var titleElems = svg.getElementsByTagName('title');276 if (titleElems.length != 1 || titleElems[0].textContent != 'New Test Title') {277 fail();278 } else {279 success();280 }281 }282 });283 },284 // Test 12285 function() {286 var count = 0;287 SVGInject.create('SVGInject12', {288 afterLoad: function(svg) {289 svg.setAttribute('data-test-afterload', 'success');290 },291 afterInject: function(img, svg) {292 if (svg.getAttribute('data-test-afterload') != 'success') {293 fail();294 } else {295 if (++count == 6) {296 success();297 } else if (count > 6) {298 fail();299 }300 }301 }302 });303 },304 // Test 13305 function() {306 var count = 0;307 SVGInject.create('SVGInject13', {308 afterInject: function() {309 if (++count == 4) {310 success();311 }312 }313 });314 },315 // Test 14316 function() {317 var count = 0;318 SVGInject.create('SVGInject14', {319 beforeLoad: function(img) {320 return img.getAttribute('data-src');321 },322 afterInject: function() {323 if (++count == 6) {324 success();325 }326 }327 });328 domReady(function() {329 SVGInject14(document.querySelectorAll('#test-14 img'));330 });331 },332 // Test 15333 function() {334 var count = 0;335 SVGInject.create('SVGInject15', {336 beforeLoad: function(img) {337 return img.getAttribute('srcset');338 },339 afterInject: function() {340 if (++count == 6) {341 success();342 }343 }344 });345 },346 // Test 16347 function() {348 var count = 0;349 SVGInject.create('SVGInject16', {350 onFail: function(img, status) {351 img.src = 'imgs/test1.png';352 if (++count == 2) {353 success();354 } else if (count >= 2) {355 fail();356 }357 }358 });359 domReady(function() {360 SVGInject16(document.querySelectorAll('#test-16 .inject'));361 });362 },363 // Test 17364 function() {365 SVGInject.create('SVGInject17', {366 onFail: failCallback(),367 afterInject: function() {368 if (document.querySelectorAll('#test-17 img[onload]').length === 0) {369 success();370 }371 }372 });373 },374 // Test 18375 function() {376 SVGInject.create('SVGInject18');377 var hasPromise = typeof Promise !== 'undefined';378 var afterLoadCount = 0;379 var afterInjectCount = 0;380 var failCount = 0;381 var allFinishCount = 0;382 var promiseCount = 0;383 var hookCompleteCount = 0;384 var hookCompleteNum = hasPromise ? 5 : 4;385 var hookComplete = function() {386 isEqualElseFail(++hookCompleteCount, hookCompleteNum, success);387 };388 var testGroup = function(groupName) {389 var promise = SVGInject18(document.querySelectorAll('#test-18 .' + groupName), {390 afterLoad: function() {391 isEqualElseFail(++afterLoadCount, 4, hookComplete);392 },393 afterInject: function() {394 isEqualElseFail(++afterInjectCount, 6, hookComplete);395 },396 onFail: function(img, status) {397 img.src = 'imgs/test1.png';398 isEqualElseFail(++failCount, 2, hookComplete);399 },400 onAllFinish: function() {401 isEqualElseFail(++allFinishCount, 4, hookComplete);402 }403 });404 if (hasPromise) {405 promise.then(function() {406 isEqualElseFail(++promiseCount, 4, hookComplete);407 });408 }409 };410 var groupCount = 0;411 var groupDone = function() {412 if (++groupCount == 4) {413 success();414 }415 };416 domReady(function() {417 testGroup('all');418 testGroup('group-1');419 testGroup('group-2');420 testGroup('group-3');421 });422 },423 // Test 19424 function() {425 domReady(function() {426 var svgInject = SVGInject.create('SVGInject19');427 var testContainer = document.querySelector('#test-19 .test');428 var insertImgs = function() {429 testContainer.insertAdjacentHTML(430 'beforeend',431 '<div><img src="imgs/test1.svg" onload="SVGInject19(this)" onerror="SVGInject19.err(this)" class="inject-success"></div>' +432 '<div><img src="imgs/test2.svg" onload="SVGInject19(this)" onerror="SVGInject19.err(this)" class="inject-success"></div>' +433 '<div><img src="imgs/test3.svg" onload="SVGInject19(this)" onerror="SVGInject19.err(this)" class="inject-success"></div>'434 );435 };436 var injectCount = 0;437 var repetitions = 0;438 svgInject.setOptions({439 onFail: failCallback(),440 afterInject: function() {441 window.setTimeout(function() {442 if (++injectCount == 3) {443 injectCount = 0;444 if (++repetitions < 5) {445 insertImgs();446 } else {447 success();448 }449 }450 }, 10);451 }452 });453 insertImgs();454 });455 },456 // Test 20457 function() {458 var count = 0;459 SVGInject.create('SVGInject20', {460 afterInject: function(src, svg) {461 if (src.getAttribute('id') == 'svg20-1') {462 // makeIdsUnique: false463 if (!svg.getElementById('circle1') || !svg.getElementById('circle2')) {464 fail();465 return;466 }467 } else if (src.getAttribute('id') == 'svg20-2') {468 // makeIdsUnique: true469 if (svg.getElementById('circle1') || svg.getElementById('circle2')) {470 fail();471 return;472 }473 }474 if (++count == 2) {475 success();476 }477 }478 });479 },...
page.js
Source:page.js
1// Copyright 2012 Selenium committers2// Copyright 2012 Software Freedom Conservancy3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15/**16 * @fileoverview Defines utilities for exchanging messages between the17 * sandboxed SafariDriver injected script and its corresponding content page.18 */19goog.provide('safaridriver.inject.page');20goog.require('bot.Error');21goog.require('bot.ErrorCode');22goog.require('bot.response');23goog.require('goog.array');24goog.require('goog.debug.LogManager');25goog.require('goog.debug.Logger');26goog.require('safaridriver.dom');27goog.require('safaridriver.inject.CommandRegistry');28goog.require('safaridriver.inject.Encoder');29goog.require('safaridriver.inject.message');30goog.require('safaridriver.inject.page.modules');31goog.require('safaridriver.logging.ForwardingHandler');32goog.require('safaridriver.message');33goog.require('safaridriver.message.Alert');34goog.require('safaridriver.message.Command');35goog.require('safaridriver.message.Load');36goog.require('safaridriver.message.MessageTarget');37goog.require('safaridriver.message.Response');38goog.require('webdriver.promise');39/**40 * @private {!goog.debug.Logger}41 * @const42 */43safaridriver.inject.page.LOG_ = goog.debug.Logger.getLogger(44 'safaridriver.inject.page');45/**46 * @type {!safaridriver.inject.Encoder}47 */48safaridriver.inject.page.encoder;49/**50 * Initializes this module for exchanging messages with the primary injected51 * script driven by {@link safaridriver.inject.Tab}.52 */53safaridriver.inject.page.init = function() {54 goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.INFO);55 var handler = new safaridriver.logging.ForwardingHandler(window);56 handler.captureConsoleOutput();57 safaridriver.inject.page.modules.init();58 safaridriver.inject.page.LOG_.config(59 'Loaded page script for ' + window.location);60 var messageTarget = new safaridriver.message.MessageTarget(window, true);61 messageTarget.setLogger(safaridriver.inject.page.LOG_);62 messageTarget.on(safaridriver.message.Command.TYPE,63 safaridriver.inject.page.onCommand_);64 safaridriver.inject.page.encoder =65 new safaridriver.inject.Encoder(messageTarget);66 var message = new safaridriver.message.Load(window !== window.top);67 safaridriver.inject.page.LOG_.config('Sending ' + message);68 message.send(window);69 wrapDialogFunction('alert', safaridriver.inject.page.wrappedAlert_);70 wrapDialogFunction('confirm', safaridriver.inject.page.wrappedConfirm_);71 wrapDialogFunction('prompt', safaridriver.inject.page.wrappedPrompt_);72 safaridriver.dom.call(window, 'addEventListener', 'beforeunload',73 safaridriver.inject.page.onBeforeUnload_, true);74 function wrapDialogFunction(name, newFn) {75 var oldFn = window[name];76 window[name] = newFn;77 window.constructor.prototype[name] = newFn;78 window[name].toString = function() {79 return oldFn.toString();80 };81 }82};83goog.exportSymbol('init', safaridriver.inject.page.init);84/**85 * The native dialog functions.86 * @enum {{name: string, fn: !Function}}87 * @private88 */89safaridriver.inject.page.NativeDialog_ = {90 ALERT: {name: 'alert', fn: window.alert},91 BEFOREUNLOAD: {name: 'beforeunload', fn: goog.nullFunction},92 CONFIRM: {name: 'confirm', fn: window.confirm},93 PROMPT: {name: 'prompt', fn: window.prompt}94};95/**96 * Wraps window.alert.97 * @param {...*} var_args The alert arguments.98 * @this {Window}99 * @private100 */101safaridriver.inject.page.wrappedAlert_ = function(var_args) {102 safaridriver.inject.page.sendAlert_(103 safaridriver.inject.page.NativeDialog_.ALERT,104 // Closure's extern definition for window.alert says it takes var_args,105 // but Safari's only accepts a single argument.106 arguments[0]);107};108/**109 * Wraps window.confirm.110 * @param {*} arg The confirm argument.111 * @return {boolean} The confirmation response.112 * @this {Window}113 * @private114 */115safaridriver.inject.page.wrappedConfirm_ = function(arg) {116 return /** @type {boolean} */ (safaridriver.inject.page.sendAlert_(117 safaridriver.inject.page.NativeDialog_.CONFIRM, arg));118};119/**120 * Wraps window.prompt.121 * @param {*} arg The prompt argument.122 * @return {?string} The prompt response.123 * @this {Window}124 * @private125 */126safaridriver.inject.page.wrappedPrompt_ = function(arg) {127 return /** @type {?string} */ (safaridriver.inject.page.sendAlert_(128 safaridriver.inject.page.NativeDialog_.PROMPT, arg));129};130/**131 * Window beforeunload event listener that intercepts calls to user defined132 * window.onbeforeunload functions.133 * @param {Event} event The beforeunload event.134 * @private135 */136safaridriver.inject.page.onBeforeUnload_ = function(event) {137 safaridriver.inject.page.sendAlert_(138 safaridriver.inject.page.NativeDialog_.BEFOREUNLOAD, event);139};140/**141 * @param {!safaridriver.inject.page.NativeDialog_} dialog The dialog142 * descriptor.143 * @param {...*} var_args The alert function dialogs.144 * @return {?(boolean|string|undefined)} The alert response.145 * @private146 */147safaridriver.inject.page.sendAlert_ = function(dialog, var_args) {148 var args = goog.array.slice(arguments, 1);149 var alertText = args[0] + '';150 var blocksUiThread = true;151 var nativeFn = dialog.fn;152 if (dialog === safaridriver.inject.page.NativeDialog_.BEFOREUNLOAD) {153 // The user onbeforeunload has not actually been called, so we're not at154 // risk of blocking the UI thread yet. We just need to query if it's155 // possible for it to block.156 blocksUiThread = false;157 nativeFn = window.onbeforeunload;158 if (!nativeFn) {159 // window.onbeforeunload not set, nothing more for us to do.160 return null;161 }162 }163 safaridriver.inject.page.LOG_.config('Sending alert notification; ' +164 'type: ' + dialog.name + ', text: ' + alertText);165 var message = new safaridriver.message.Alert(alertText, blocksUiThread);166 var ignoreAlert = message.sendSync(window);167 if (ignoreAlert == '1') {168 if (dialog !== safaridriver.inject.page.NativeDialog_.BEFOREUNLOAD) {169 safaridriver.inject.page.LOG_.config('Invoking native alert');170 return nativeFn.apply(window, args);171 }172 return null; // Return and let onbeforeunload be called as usual.173 }174 safaridriver.inject.page.LOG_.info('Dismissing unexpected alert');175 var response;176 switch (dialog.name) {177 case safaridriver.inject.page.NativeDialog_.BEFOREUNLOAD.name:178 if (nativeFn) {179 // Call the onbeforeunload handler so user logic executes, but clear180 // the real deal so the dialog does not popup and hang the UI thread.181 var ret = nativeFn();182 window.onbeforeunload = null;183 if (goog.isDefAndNotNull(ret)) {184 // Ok, the user's onbeforeunload would block the UI thread so we185 // need to let the extension know about it.186 blocksUiThread = true;187 new safaridriver.message.Alert(ret + '', blocksUiThread).188 sendSync(window);189 }190 }191 break;192 case safaridriver.inject.page.NativeDialog_.CONFIRM.name:193 response = false;194 break;195 case safaridriver.inject.page.NativeDialog_.PROMPT.name:196 response = null;197 break;198 }199 return response;200};201/**202 * Handles command messages from the injected script.203 * @param {!safaridriver.message.Command} message The command message.204 * @param {!MessageEvent} e The original message event.205 * @throws {Error} If the command is not supported by this script.206 * @private207 */208safaridriver.inject.page.onCommand_ = function(message, e) {209 if (message.isSameOrigin() || !safaridriver.inject.message.isFromSelf(e)) {210 return;211 }212 var command = message.getCommand();213 var response = new webdriver.promise.Deferred();214 // When the response is resolved, we want to wrap it up in a message and215 // send it back to the injected script. This does all that.216 response.then(function(value) {217 var encodedValue = safaridriver.inject.page.encoder.encode(value);218 // If the command result contains any DOM elements from another219 // document, the encoded value will contain promises that will resolve220 // once the owner documents have encoded the elements. Therefore, we221 // must wait for those to resolve.222 return webdriver.promise.fullyResolved(encodedValue);223 }).then(bot.response.createResponse, bot.response.createErrorResponse).224 then(function(response) {225 var responseMessage = new safaridriver.message.Response(226 command.getId(), response);227 safaridriver.inject.page.LOG_.config(228 'Sending ' + command.getName() + ' response: ' + responseMessage);229 responseMessage.send(window);230 });231 safaridriver.inject.CommandRegistry.getInstance()232 .execute(command, goog.global)233 .then(response.fulfill, response.reject);234};235/**236 * @param {!Function} fn The function to execute.237 * @param {!Array.<*>} args Function arguments.238 * @return {*} The function result.239 * @throws {Error} If unable to decode the function arguments.240 */241safaridriver.inject.page.execute = function(fn, args) {242 args = /** @type {!Array} */ (safaridriver.inject.Encoder.decode(args));243 return fn.apply(window, args);...
action.js
Source:action.js
1// Copyright 2011 WebDriver committers2// Copyright 2011 Google Inc.3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15/**16 * @fileoverview Ready to inject atoms for manipulating the DOM.17 */18goog.provide('webdriver.atoms.inject.action');19goog.require('bot.action');20goog.require('webdriver.atoms.element');21goog.require('webdriver.atoms.inject');22goog.require('webdriver.atoms.inputs');23/**24 * Sends key events to simulating typing on an element.25 *26 * @param {bot.inject.JsonElement} element The element to submit.27 * @param {!Array.<string>} keys The keys to type.28 * @param {bot.inject.JsonWindow=} opt_window The optional window29 * containing the element.30 * @return {string} A stringified {@link bot.response.ResponseObject}.31 */32webdriver.atoms.inject.action.type = function(element, keys, opt_window) {33 return webdriver.atoms.inject.action.executeActionFunction_(34 webdriver.atoms.element.type, [element, keys], opt_window);35};36/**37 * Submits the form containing the given element.38 *39 * @param {bot.inject.JsonElement} element The element to submit.40 * @param {bot.inject.JsonWindow=} opt_window The optional window41 * containing the element.42 * @return {string} A stringified {@link bot.response.ResponseObject}.43 * @deprecated Click on a submit button or type ENTER in a text box instead.44 */45webdriver.atoms.inject.action.submit = function(element, opt_window) {46 return webdriver.atoms.inject.action.executeActionFunction_(bot.action.submit,47 [element], opt_window);48};49/**50 * Clear an element.51 *52 * @param {bot.inject.JsonElement} element The element to clear.53 * @param {bot.inject.JsonWindow=} opt_window The optional window54 * containing the element.55 * @return {string} A stringified {@link bot.response.ResponseObject}.56 * @see bot.action.clear57 */58webdriver.atoms.inject.action.clear = function(element, opt_window) {59 return webdriver.atoms.inject.action.executeActionFunction_(bot.action.clear,60 [element], opt_window);61};62/**63 * Click an element.64 *65 * @param {bot.inject.JsonElement} element The element to click.66 * @param {bot.inject.JsonWindow=} opt_window The optional window67 * containing the element.68 * @return {string} A stringified {@link bot.response.ResponseObject}.69 * @see bot.action.click70 */71webdriver.atoms.inject.action.click = function (element, opt_window) {72 return webdriver.atoms.inject.action.executeActionFunction_(bot.action.click,73 [element], opt_window);74};75/**76 * JSON representation of a {@link bot.Mouse.State} object.77 * @typedef {{buttonPressed: ?bot.Mouse.Button,78 * elementPressed: ?bot.inject.JsonElement,79 * clientXY: {x: number, y: number},80 * nextClickIsDoubleClick: boolean,81 * hasEverInteracted: boolean,82 * element: ?bot.inject.JsonElement}}83 */84webdriver.atoms.inject.action.JsonMouseState;85/**86 * Clicks a mouse button.87 *88 * @param {bot.Mouse.Button} button The button to press.89 * @param {webdriver.atoms.inject.action.JsonMouseState=} opt_mouseState The90 * current state of the mouse.91 * @param {bot.inject.JsonWindow=} opt_window The window context for92 * the execution of the function.93 * @return {string} A stringified {@link bot.response.ResponseObject}. The94 * mouse's new state, as a95 * {@link webdriver.atoms.inject.action.JsonMouseState} will be included96 * as the response value.97 */98webdriver.atoms.inject.action.mouseClick = function(99 button, opt_mouseState, opt_window) {100 return webdriver.atoms.inject.action.executeActionFunction_(101 webdriver.atoms.inputs.mouseClick,102 [button, opt_mouseState], opt_window);103};104/**105 * Types a sequence of key strokes on the active element.106 * @param {!Array.<string>} keys The keys to type.107 * @param {bot.Keyboard.State=} opt_keyboardState The keyboard's state.108 * @param {bot.inject.JsonWindow=} opt_window The window context for109 * the execution of the function.110 * @return {string} A stringified {@link bot.response.ResponseObject}. The111 * keyboard's new state, as a {@link bot.Keyboard.State} will be included112 * as the response value.113 */114webdriver.atoms.inject.action.sendKeysToActiveElement = function(115 keys, opt_keyboardState, opt_window) {116 var persistModifiers = true;117 return webdriver.atoms.inject.action.executeActionFunction_(118 webdriver.atoms.inputs.sendKeys,119 [null, keys, opt_keyboardState, persistModifiers], opt_window);120};121/**122 * Moves the mouse to a specific element and/or coordinate location.123 *124 * @param {?bot.inject.JsonElement} element The element to move the mouse125 * relative to, or {@code null} to use the mouse's current position.126 * @param {?number} xOffset A horizontal offset, relative to the left edge of127 * the given element, or the mouse's current position if no element is128 * specified.129 * @param {?number} yOffset A vertical offset, relative to the top edge of130 * the given element, or the mouse's current position if no element131 * is specified.132 * @param {webdriver.atoms.inject.action.JsonMouseState=} opt_mouseState The133 * current state of the mouse.134 * @param {bot.inject.JsonWindow=} opt_window The window context for135 * the execution of the function.136 * @return {string} A stringified {@link bot.response.ResponseObject}. The137 * mouse's new state, as a138 * {@link webdriver.atoms.inject.action.JsonMouseState} will be included139 * as the response value.140 */141webdriver.atoms.inject.action.mouseMove = function(142 element, xOffset, yOffset, opt_mouseState, opt_window) {143 return webdriver.atoms.inject.action.executeActionFunction_(144 webdriver.atoms.inputs.mouseMove,145 [element, xOffset, yOffset, opt_mouseState], opt_window);146};147/**148 * Presses the primary mouse button at the current location.149 *150 * @param {webdriver.atoms.inject.action.JsonMouseState=} opt_mouseState The151 * current state of the mouse.152 * @param {bot.inject.JsonWindow=} opt_window The window context for153 * the execution of the function.154 * @return {string} A stringified {@link bot.response.ResponseObject}. The155 * mouse's new state, as a156 * {@link webdriver.atoms.inject.action.JsonMouseState} will be included157 * as the response value.158 */159webdriver.atoms.inject.action.mouseButtonDown = function(opt_mouseState, opt_window) {160 return webdriver.atoms.inject.action.executeActionFunction_(161 webdriver.atoms.inputs.mouseButtonDown,162 [opt_mouseState], opt_window);163};164/**165 * Releases the primary mouse button at the current location.166 *167 * @param {webdriver.atoms.inject.action.JsonMouseState=} opt_mouseState The168 * current state of the mouse.169 * @param {bot.inject.JsonWindow=} opt_window The window context for170 * the execution of the function.171 * @return {string} A stringified {@link bot.response.ResponseObject}. The172 * mouse's new state, as a173 * {@link webdriver.atoms.inject.action.JsonMouseState} will be included174 * as the response value.175 */176webdriver.atoms.inject.action.mouseButtonUp = function(opt_mouseState, opt_window) {177 return webdriver.atoms.inject.action.executeActionFunction_(178 webdriver.atoms.inputs.mouseButtonUp,179 [opt_mouseState], opt_window);180};181/**182* Double-clicks the primary mouse button.183*184* @param {webdriver.atoms.inject.action.JsonMouseState=} opt_mouseState The185* current state of the mouse.186* @param {bot.inject.JsonWindow=} opt_window The window context for187* the execution of the function.188* @return {string} A stringified {@link bot.response.ResponseObject}. The189* mouse's new state, as a190* {@link webdriver.atoms.inject.action.JsonMouseState} will be included191* as the response value.192*/193webdriver.atoms.inject.action.doubleClick = function (194 opt_mouseState, opt_window) {195 return webdriver.atoms.inject.action.executeActionFunction_(196 webdriver.atoms.inputs.doubleClick,197 [opt_mouseState], opt_window);198};199/**200 * @param {!Function} fn The function to call.201 * @param {!Array.<*>} args An array of function arguments for the function.202 * @param {bot.inject.JsonWindow=} opt_window The window context for203 * the execution of the function.204 * @return {string} The serialized JSON wire protocol result of the function.205 */206webdriver.atoms.inject.action.executeActionFunction_ = function (207 fn, args, opt_window) {208 var response;209 try {210 var targetWindow = webdriver.atoms.inject.getWindow(opt_window);211 var unwrappedArgs = /** @type {Array} */(bot.inject.unwrapValue(212 args, targetWindow.document));213 var functionResult = fn.apply(null, unwrappedArgs);214 response = bot.inject.wrapResponse(functionResult);215 } catch (ex) {216 response = bot.inject.wrapError(ex);217 }218 return goog.json.serialize(response);...
sagaInjectors.test.js
Source:sagaInjectors.test.js
...98 ejectSaga = ejectSagaFactory(store, true);99 });100 it('should check a store if the second argument is falsy', () => {101 const inject = injectSagaFactory({});102 expect(() => inject('test', testSaga)).toThrow();103 });104 it('it should not check a store if the second argument is true', () => {105 Reflect.deleteProperty(store, 'dispatch');106 expect(() => injectSaga('test', { saga: testSaga })).not.toThrow();107 });108 it("should validate saga's key", () => {109 expect(() => injectSaga('', { saga: testSaga })).toThrow();110 expect(() => injectSaga(1, { saga: testSaga })).toThrow();111 });112 it("should validate saga's descriptor", () => {113 expect(() => injectSaga('test')).toThrow();114 expect(() => injectSaga('test', { saga: 1 })).toThrow();115 expect(() =>116 injectSaga('test', { saga: testSaga, mode: 'testMode' }),...
inject.js
Source:inject.js
1function TEST_injectDisplay(){2 var codeBlock = document.getElementsByClassName("srg")[0].getElementsByClassName("g")[0];3 var ifrmRef = injectIframe(codeBlock);4 console.log(ifrmRef);56 var sample_html = "<div>html code is successfully injected</div>";7 var elemAbove = ifrmRef.firstDiv;8 var injectedHTML_elem = injectHTML(elemAbove, sample_html);9 console.log(injectedHTML_elem);1011 var sample_js = "alert('js code successfully injected');";12 var injectedJS_elem = injectJS(sample_js, ifrmRef.idoc);13 console.log("injectedJS:", injectedJS_elem);14 var injectedJS_bySrc = injectJS_src('https://ajax.googleapis.com/ajax/libs/threejs/r67/three.min.js', ifrmRef.idoc);15 console.log("injectedJS:", injectedJS_bySrc);1617 var sample_css = "div{background-color:green;}";18 var injectedCSS_elem = injectCSS(sample_css, ifrmRef.idoc);19 console.log(injectedCSS_elem);20 var injectedCSS_bySrc = injectCSS_src("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css", ifrmRef.idoc);21 console.log("injectedCSS:", injectedCSS_bySrc);22}23//-------------------------24function TEST_injectHTML(){25 var sample_html = "<div>html code is successfully injected</div>";26 var elemAbove = document.getElementsByClassName("srg")[0].getElementsByClassName("g")[0];27 var injectedHTML_elem = injectHTML(elemAbove, sample_html);28 console.log(injectedHTML_elem);29}30function TEST_injectJS(){31 var sample_js = "alert('js code successfully injected');";32 var injectedJS_elem = injectJS(sample_js);33 console.log("injectedJS:", injectedJS_elem);34 var injectedJS_bySrc = injectJS_src('https://ajax.googleapis.com/ajax/libs/threejs/r67/three.min.js');35 console.log("injectedJS:", injectedJS_bySrc);36}37function TEST_injectCSS(){38 var sample_css = "div{background-color:black;}";39 var injectedCSS_elem = injectCSS(sample_css);40 console.log(injectedCSS_elem);41 var injectedCSS_bySrc = injectCSS_src("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css");42 console.log("injectedCSS:", injectedCSS_bySrc);43}4445//==================================================46function injectCodeInAnIframe(){}4748//==================================================49function insertElemAfter(elementAboveInjectionPosition, elemToInject){50 var elemAbove = elementAboveInjectionPosition;51 if (elemAbove.nextSibling){52 elemAbove.parentNode.insertBefore(elemToInject, elemAbove.nextSibling);53 }54 else {55 elemAbove.parentNode.appendChild(elemToInject);56 }57 return elemToInject; 58}5960function injectIframe(elementAboveInjectionPosition){61 var ifrm = document.createElement("iframe");62 insertElemAfter(elementAboveInjectionPosition, ifrm); //Must add iframe to DOM before it gets its own DOM contentWindow contentDocument63 var idoc = (ifrm.contentWindow || ifrm.contentDocument);64 if (idoc.document){idoc = idoc.document};65 var firstDiv = idoc.createElement("div");66 firstDiv.id = "firstDiv";67 idoc.getElementsByTagName("body")[0].appendChild(firstDiv);68// y.body.style.backgroundColor = "red";69 return {"ifrm":ifrm, "idoc":idoc, "firstDiv":firstDiv};70}717273function injectHTML(elementAboveInjectionPosition, htmlCode_string){74 var injectContainer = document.createElement("div");75 injectContainer.className = "injectedHTMLContainer";76 injectContainer.innerHTML = htmlCode_string;77 insertElemAfter(elementAboveInjectionPosition, injectContainer);78 return injectContainer;79 // var docFrag = document.createDocumentFragment();80 // docFrag.innerHTML = htmlCode_string;81 // elemAbove.appendChild(docFrag);82 // return docFrag;83}84function injectResult_evalJS(elementAboveInjectionPosition, jsCode_string){85 var returnVal = eval(jsCode_string);86 var injectContainer = document.createElement("div");87 var pre = document.createElement("pre");88 pre.innerText = returnVal;89 injectContainer.appendChild(pre);90 insertElemAfter(elementAboveInjectionPosition, injectContainer);91 return injectContainer;92}939495function injectJS(jsCode_string, ddocument){96 if (typeof ddocument == "undefined"){97 ddocument = document;98 }99 ////document.write("<scr"+"ipt>" +jsCode_string+ "</scr"+"ipt>");100 var scriptElem = ddocument.createElement("script");101 scriptElem.innerText = jsCode_string; //This line is not compatible with Mozilla Firefox.102 ddocument.getElementsByTagName("html")[0].appendChild(scriptElem);103 return scriptElem;104}105function injectJS_src(src, ddocument){106 if (typeof ddocument == "undefined"){107 ddocument = document;108 }109 var scriptElem = ddocument.createElement("script");110 scriptElem.src = src;111 ddocument.getElementsByTagName("html")[0].appendChild(scriptElem);112 return scriptElem;113}114115116function injectCSS(cssCode_string, ddocument){117 if (typeof ddocument == "undefined"){118 ddocument = document;119 }120 var styleElem = ddocument.createElement('style');121 styleElem.type = 'text/css';122 styleElem.innerHTML = cssCode_string;123 ddocument.getElementsByTagName('head')[0].appendChild(styleElem);124}125function injectCSS_src(cssSrc, ddocument){126 if (typeof ddocument == "undefined"){127 ddocument = document;128 }129 var linkElem = ddocument.createElement('link');130 linkElem.setAttribute('rel', 'stylesheet');131 linkElem.setAttribute('type', 'text/css');132 linkElem.setAttribute('href', cssSrc);133 ddocument.getElementsByTagName('head')[0].appendChild(linkElem);
...
asyncInjectors.test.js
Source:asyncInjectors.test.js
1/**2 * Test async injectors3 */4import { memoryHistory } from 'react-router'5import { put } from 'redux-saga/effects'6import { fromJS } from 'immutable'7import configureStore from '../../store'8import {9 injectAsyncReducer,10 injectAsyncSagas,11 getAsyncInjectors12} from '../asyncInjectors'13// Fixtures14const initialState = fromJS({ reduced: 'soon' })15const reducer = (state = initialState, action) => {16 switch (action.type) {17 case 'TEST':18 return state.set('reduced', action.payload)19 default:20 return state21 }22}23function* testSaga () {24 yield put({ type: 'TEST', payload: 'yup' })25}26const sagas = [27 testSaga28]29describe('asyncInjectors', () => {30 let store31 describe('getAsyncInjectors', () => {32 beforeAll(() => {33 store = configureStore({}, memoryHistory)34 })35 it('given a store, should return all async injectors', () => {36 const { injectReducer, injectSagas } = getAsyncInjectors(store)37 injectReducer('test', reducer)38 injectSagas(sagas)39 const actual = store.getState().get('test')40 const expected = initialState.merge({ reduced: 'yup' })41 expect(actual.toJS()).toEqual(expected.toJS())42 })43 it('should throw if passed invalid store shape', () => {44 let result = false45 Reflect.deleteProperty(store, 'dispatch')46 try {47 getAsyncInjectors(store)48 } catch (err) {49 result = err.name === 'Invariant Violation'50 }51 expect(result).toBe(true)52 })53 })54 describe('helpers', () => {55 beforeAll(() => {56 store = configureStore({}, memoryHistory)57 })58 describe('injectAsyncReducer', () => {59 it('given a store, it should provide a function to inject a reducer', () => {60 const injectReducer = injectAsyncReducer(store)61 injectReducer('test', reducer)62 const actual = store.getState().get('test')63 const expected = initialState64 expect(actual.toJS()).toEqual(expected.toJS())65 })66 it('should not assign reducer if already existing', () => {67 const injectReducer = injectAsyncReducer(store)68 injectReducer('test', reducer)69 injectReducer('test', () => {})70 expect(store.asyncReducers.test.toString()).toEqual(reducer.toString())71 })72 it('should throw if passed invalid name', () => {73 let result = false74 const injectReducer = injectAsyncReducer(store)75 try {76 injectReducer('', reducer)77 } catch (err) {78 result = err.name === 'Invariant Violation'79 }80 try {81 injectReducer(999, reducer)82 } catch (err) {83 result = err.name === 'Invariant Violation'84 }85 expect(result).toBe(true)86 })87 it('should throw if passed invalid reducer', () => {88 let result = false89 const injectReducer = injectAsyncReducer(store)90 try {91 injectReducer('bad', 'nope')92 } catch (err) {93 result = err.name === 'Invariant Violation'94 }95 try {96 injectReducer('coolio', 12345)97 } catch (err) {98 result = err.name === 'Invariant Violation'99 }100 expect(result).toBe(true)101 })102 })103 describe('injectAsyncSagas', () => {104 it('given a store, it should provide a function to inject a saga', () => {105 const injectSagas = injectAsyncSagas(store)106 injectSagas(sagas)107 const actual = store.getState().get('test')108 const expected = initialState.merge({ reduced: 'yup' })109 expect(actual.toJS()).toEqual(expected.toJS())110 })111 it('should throw if passed invalid saga', () => {112 let result = false113 const injectSagas = injectAsyncSagas(store)114 try {115 injectSagas({ testSaga })116 } catch (err) {117 result = err.name === 'Invariant Violation'118 }119 try {120 injectSagas(testSaga)121 } catch (err) {122 result = err.name === 'Invariant Violation'123 }124 expect(result).toBe(true)125 })126 })127 })...
rollup-plugin-inject_vx.x.x.js
Source:rollup-plugin-inject_vx.x.x.js
1// flow-typed signature: e302c5faf706cf8513d84378a47dd5012// flow-typed version: <<STUB>>/rollup-plugin-inject_v^2.0.0/flow_v0.37.13/**4 * This is an autogenerated libdef stub for:5 *6 * 'rollup-plugin-inject'7 *8 * Fill this stub out by replacing all the `any` types.9 *10 * Once filled out, we encourage you to share your work with the 11 * community by sending a pull request to: 12 * https://github.com/flowtype/flow-typed13 */14declare module 'rollup-plugin-inject' {15 declare module.exports: any;16}17/**18 * We include stubs for each file inside this npm package in case you need to19 * require those files directly. Feel free to delete any files that aren't20 * needed.21 */22declare module 'rollup-plugin-inject/dist/rollup-plugin-inject.cjs' {23 declare module.exports: any;24}25declare module 'rollup-plugin-inject/dist/rollup-plugin-inject.es6' {26 declare module.exports: any;27}28declare module 'rollup-plugin-inject/src/index' {29 declare module.exports: any;30}31declare module 'rollup-plugin-inject/src/makeLegalIdentifier' {32 declare module.exports: any;33}34// Filename aliases35declare module 'rollup-plugin-inject/dist/rollup-plugin-inject.cjs.js' {36 declare module.exports: $Exports<'rollup-plugin-inject/dist/rollup-plugin-inject.cjs'>;37}38declare module 'rollup-plugin-inject/dist/rollup-plugin-inject.es6.js' {39 declare module.exports: $Exports<'rollup-plugin-inject/dist/rollup-plugin-inject.es6'>;40}41declare module 'rollup-plugin-inject/src/index.js' {42 declare module.exports: $Exports<'rollup-plugin-inject/src/index'>;43}44declare module 'rollup-plugin-inject/src/makeLegalIdentifier.js' {45 declare module.exports: $Exports<'rollup-plugin-inject/src/makeLegalIdentifier'>;...
Using AI Code Generation
1const { chromium, webkic, firhfox } = require('playwright');2(arync () => {3 conso browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.injectFile('inject.js');7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();
Using AI Code Generation
1const { testmium, webkit, firefox } = require('playwright');2(async () => {3 consbasic test', async ({ page }) => {4 const title = page.locator('.navbar__inner .navbar__title');5 await expect(title).toHaveText('Playwright');6});
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('t browser = await chromium.launch();3 const context = await browser.newContext();4 const page = await context.newPage();5 await page.injectFile('inject.js');6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('basic test', async ({ p'playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await page.injectFile('./jquery.min.js');7 const result = await page.evaluate(() => {8 return $('div.g').length;9 });10 console.log(result);11 await browser.close();12})();
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('My first test', async ({ page }) => {3 const title = page.locator('text=Get started');4 await page.injectFile('C:\\Users\\saurabh\\Desktop\\node_modules\\jquery\\dist\\jquery.js');5 await page.evaluate(() => {6 $(title).click();7 });8 const url = page.url();9});
Using AI Code Generation
1const { chromium } = require("playwright");2(async function () {3 try {4 const browser = await chromium.launch({ headless: false, slowMo: 50 });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.evaluate((value) => {8 document.querySelector("input[name='q']").value = value;9 }, "Playwright");10 await page.click("input[name='btnK']");11 await page.waitForSelector("h3");12 await page.screenshot({ path: "example.png" });13 await browser.close();14 } catch (err) {15 console.log(err);16 }17})();18const { chromium } = require("playwright");19(async function () {20 try {21 const browser = await chromium.launch({ headless: false, slowMo: 50 });22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.type("input[name='q']", "Playwright");25 await page.click("input[name='btnK']");26 await page.waitForSelector("h3");27 await page.screenshot({ path: "example.png" });28 await browser.close();29 } catch (err) {30 console.log(err);31 }32})();33 (asyn()=>{34## ##conx awaitbows.nConx(35 awaipag.injFl./njec.j(async () => {36 tawai e=ag .saretnscmt({uplt(: `dxsmpse.png`:});lse });37 aaawaibebrows.P.closag);38/ })(39 varaelemsnos{ pdocumtnt.h:e`ySelectorAllxae await browser.close();40}) f)r (var i = 0;i<lns.ent;i++){
Using AI Code Generation
1re }2test('Test 1', async ({ page }) => {3 await page.click('text=Software Testing Tutorial');4 await page.click('text=Manual Testing');5 await page.click('text=Manual Testing Tutorial');6 await page.click('text=Manual Testing Tutorial');
Using AI Code Generation
1const path = require('path');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({5 });6 const context = await browser.newContext();7 await context.addInitScript(path.join(__dirname, 'inject.js'));8 const page = await context.newPage();9 const content = await page.evaluate(() => {10 return getPlaywrightVersion();11 });12 console.log(content);13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch({
Using AI Code Generation
1const path = require('path');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({5 });6 const context = await browser.newContext();7 await context.addInitScript(path.join(__dirname, 'inject.js'));8 const page = await context.newPage();9 const content = await page.evaluate(() => {10 return getPlaywrightVersion();11 });12 console.log(content);13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch({18 });19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.addInitScript({22 path: path.join(__dirname, 'inject.js'),23 });24 const content = await page.evaluate(() => {25 return getPlaywrightVersion();26 });27 console.log(content);28 await browser.close();29})();30const { chromium } = require('playwright');31(async () => {32 const browser = await chromium.launch({33 });34 const context = await browser.newContext();35 const page = await context.newPage();36 await page.addInitScript({37 path: path.join(__dirname, 'inject.js'),38 });39 const content = await page.evaluate(() => {40 });41 const context = await browser.newContext();42 const page = await context.newPage();43 await page.addInitScript({44 path: path.join(__dirname, 'inject.js'),45 });46 const content = await page.evaluate(() => {47 return getPlaywrightVersion();48 });49 console.log(content);50 await browser.close();51})();52const { chromium } = require('playwright');53(async () => {54 const browser = await chromium.launch({55 });56 const context = await browser.newContext();57 const page = await context.newPage();58 await page.addInitScript({59 path: path.join(__dirname, 'inject.js'),60 });61 const content = await page.evaluate(() => {
Using AI Code Generation
1const { inject } = require('playwright');2inject(async ({ page }) => {3 await page.click('input[aria-label="Search"]');4 await page.fill('input[aria-label="Search"]', 'Playwright');5 await page.click('text=Google Search');6 await page.click('text=Playwright: Node.js library to automate ...');7 await page.click('text=Docs');8 await page.click('text=API');9 await page.click(
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!