How to use _document method in Puppeteer

Best JavaScript code snippet using puppeteer

renderPaymentMethod.js

Source:renderPaymentMethod.js Github

copy

Full Screen

1"use strict";2var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));3function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }4function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }5function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }6function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }7function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }8function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }9var store = require('../../../../store');10var helpers = require('./helpers');11var _require = require('./qrCodeMethods'),12 qrCodeMethods = _require.qrCodeMethods;13function getFallback(paymentMethod) {14 var fallback = {15 giftcard: "\n <input type=\"hidden\" class=\"brand\" name=\"brand\" value=\"".concat(paymentMethod.brand, "\"/>\n <input type=\"hidden\" class=\"type\" name=\"type\" value=\"").concat(paymentMethod.type, "\"/>")16 };17 if (fallback[paymentMethod.type]) {18 store.componentsObj[paymentMethod.type] = {};19 }20 return fallback[paymentMethod.type];21}22function getPersonalDetails() {23 var _document$querySelect, _document$querySelect2, _document$querySelect3, _document$querySelect4, _document$querySelect5, _document$querySelect6, _document$querySelect7, _document$querySelect8, _document$querySelect9, _document$querySelect10, _document$querySelect11, _document$querySelect12, _document$querySelect13, _document$querySelect14, _document$querySelect15, _document$querySelect16;24 return {25 firstName: (_document$querySelect = document.querySelector('#shippingFirstNamedefault')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.value,26 lastName: (_document$querySelect2 = document.querySelector('#shippingLastNamedefault')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value,27 telephoneNumber: (_document$querySelect3 = document.querySelector('#shippingPhoneNumberdefault')) === null || _document$querySelect3 === void 0 ? void 0 : _document$querySelect3.value,28 shopperEmail: (_document$querySelect4 = document.querySelector('.customer-summary-email')) === null || _document$querySelect4 === void 0 ? void 0 : _document$querySelect4.textContent,29 billingAddress: {30 city: (_document$querySelect5 = document.querySelector('#billingAddressCity')) === null || _document$querySelect5 === void 0 ? void 0 : _document$querySelect5.value,31 postalCode: (_document$querySelect6 = document.querySelector('#billingZipCode')) === null || _document$querySelect6 === void 0 ? void 0 : _document$querySelect6.value,32 country: (_document$querySelect7 = document.querySelector('#billingCountry')) === null || _document$querySelect7 === void 0 ? void 0 : _document$querySelect7.value,33 stateOrProvince: (_document$querySelect8 = document.querySelector('#billingState')) === null || _document$querySelect8 === void 0 ? void 0 : _document$querySelect8.value,34 street: (_document$querySelect9 = document.querySelector('#billingAddressOne')) === null || _document$querySelect9 === void 0 ? void 0 : _document$querySelect9.value,35 houseNumberOrName: (_document$querySelect10 = document.querySelector('#billingAddressTwo')) === null || _document$querySelect10 === void 0 ? void 0 : _document$querySelect10.value36 },37 deliveryAddress: {38 city: (_document$querySelect11 = document.querySelector('#shippingAddressCitydefault')) === null || _document$querySelect11 === void 0 ? void 0 : _document$querySelect11.value,39 postalCode: (_document$querySelect12 = document.querySelector('#shippingZipCodedefault')) === null || _document$querySelect12 === void 0 ? void 0 : _document$querySelect12.value,40 country: (_document$querySelect13 = document.querySelector('#shippingCountrydefault')) === null || _document$querySelect13 === void 0 ? void 0 : _document$querySelect13.value,41 stateOrProvince: (_document$querySelect14 = document.querySelector('#shippingStatedefault')) === null || _document$querySelect14 === void 0 ? void 0 : _document$querySelect14.value,42 street: (_document$querySelect15 = document.querySelector('#shippingAddressOnedefault')) === null || _document$querySelect15 === void 0 ? void 0 : _document$querySelect15.value,43 houseNumberOrName: (_document$querySelect16 = document.querySelector('#shippingAddressTwodefault')) === null || _document$querySelect16 === void 0 ? void 0 : _document$querySelect16.value44 }45 };46}47function setNode(paymentMethodID) {48 var createNode = function createNode() {49 if (!store.componentsObj[paymentMethodID]) {50 store.componentsObj[paymentMethodID] = {};51 }52 try {53 var _store$checkout;54 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {55 args[_key] = arguments[_key];56 }57 // ALl nodes created for the checkout component are enriched with shopper personal details58 var node = (_store$checkout = store.checkout).create.apply(_store$checkout, args.concat([{59 data: _objectSpread(_objectSpread({}, getPersonalDetails()), {}, {60 personalDetails: getPersonalDetails()61 })62 }]));63 store.componentsObj[paymentMethodID].node = node;64 } catch (e) {65 /* No component for payment method */66 }67 };68 return createNode;69}70function getPaymentMethodID(isStored, paymentMethod) {71 if (isStored) {72 return "storedCard".concat(paymentMethod.id);73 }74 if (paymentMethod.brand) {75 // gift cards all share the same type. Brand is used to differentiate between them76 return "".concat(paymentMethod.type, "_").concat(paymentMethod.brand);77 }78 return paymentMethod.type;79}80function getImage(isStored, paymentMethod) {81 return isStored ? paymentMethod.brand : paymentMethod.type;82}83function getLabel(isStored, paymentMethod) {84 var label = isStored ? " ".concat(store.MASKED_CC_PREFIX).concat(paymentMethod.lastFour) : '';85 return "".concat(paymentMethod.name).concat(label);86}87function handleFallbackPayment(_ref) {88 var paymentMethod = _ref.paymentMethod,89 container = _ref.container,90 paymentMethodID = _ref.paymentMethodID;91 var fallback = getFallback(paymentMethod);92 var createTemplate = function createTemplate() {93 var template = document.createElement('template');94 template.innerHTML = fallback;95 container.append(template.content);96 };97 return fallback ? createTemplate() : setNode(paymentMethod.type)(paymentMethodID);98}99function handlePayment(options) {100 return options.isStored ? setNode(options.paymentMethodID)('card', options.paymentMethod) : handleFallbackPayment(options);101}102function getListContents(_ref2) {103 var imagePath = _ref2.imagePath,104 isStored = _ref2.isStored,105 paymentMethod = _ref2.paymentMethod,106 description = _ref2.description;107 var paymentMethodID = getPaymentMethodID(isStored, paymentMethod);108 var label = getLabel(isStored, paymentMethod);109 var liContents = "\n <input name=\"brandCode\" type=\"radio\" value=\"".concat(paymentMethodID, "\" id=\"rb_").concat(paymentMethodID, "\">\n <img class=\"paymentMethod_img\" src=\"").concat(imagePath, "\" ></img>\n <label id=\"lb_").concat(paymentMethodID, "\" for=\"rb_").concat(paymentMethodID, "\">").concat(label, "</label>\n ");110 return description ? "".concat(liContents, "<p>").concat(description, "</p>") : liContents;111}112function getImagePath(_ref3) {113 var isStored = _ref3.isStored,114 paymentMethod = _ref3.paymentMethod,115 path = _ref3.path,116 isSchemeNotStored = _ref3.isSchemeNotStored;117 var paymentMethodImage = "".concat(path).concat(getImage(isStored, paymentMethod), ".png");118 var cardImage = "".concat(path, "card.png");119 return isSchemeNotStored ? cardImage : paymentMethodImage;120}121function hasNoChildNodes(_ref4) {122 var paymentMethodID = _ref4.paymentMethodID,123 container = _ref4.container;124 return store.componentsObj[paymentMethodID] && !container.childNodes[0];125}126function setValid(_ref5) {127 var paymentMethodID = _ref5.paymentMethodID,128 container = _ref5.container;129 if (hasNoChildNodes({130 paymentMethodID: paymentMethodID,131 container: container132 }) && ['bcmc', 'scheme'].indexOf(paymentMethodID) === -1) {133 store.componentsObj[paymentMethodID].isValid = true;134 }135}136function configureContainer(_ref6) {137 var paymentMethodID = _ref6.paymentMethodID,138 container = _ref6.container;139 container.classList.add('additionalFields');140 container.setAttribute('id', "component_".concat(paymentMethodID));141 container.setAttribute('style', 'display:none');142}143function handleInput(_ref7) {144 var paymentMethodID = _ref7.paymentMethodID;145 var input = document.querySelector("#rb_".concat(paymentMethodID));146 input.onchange = /*#__PURE__*/function () {147 var _ref8 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(event) {148 var _store$componentsObj$, compName, qrComponent, node;149 return _regenerator["default"].wrap(function _callee$(_context) {150 while (1) {151 switch (_context.prev = _context.next) {152 case 0:153 if (!(document.querySelector('.adyen-checkout__qr-loader') && qrCodeMethods.indexOf(store.selectedMethod) > -1)) {154 _context.next = 10;155 break;156 }157 compName = store.selectedMethod;158 qrComponent = store.componentsObj[compName];159 _context.next = 5;160 return Promise.resolve(qrComponent.node.unmount("component_".concat(compName)));161 case 5:162 delete store.componentsObj[compName];163 setNode(compName)(compName);164 node = (_store$componentsObj$ = store.componentsObj[compName]) === null || _store$componentsObj$ === void 0 ? void 0 : _store$componentsObj$.node;165 if (node) {166 node.mount(document.querySelector("#component_".concat(compName)));167 }168 helpers.paymentFromComponent({169 cancelTransaction: true,170 merchantReference: document.querySelector('#merchantReference').value171 });172 case 10:173 helpers.displaySelectedMethod(event.target.value);174 case 11:175 case "end":176 return _context.stop();177 }178 }179 }, _callee);180 }));181 return function (_x) {182 return _ref8.apply(this, arguments);183 };184 }();185}186module.exports.renderPaymentMethod = function renderPaymentMethod(paymentMethod, isStored, path) {187 var _store$componentsObj$2;188 var description = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;189 var paymentMethodsUI = document.querySelector('#paymentMethodsList');190 var li = document.createElement('li');191 var paymentMethodID = getPaymentMethodID(isStored, paymentMethod);192 var isSchemeNotStored = paymentMethod.type === 'scheme' && !isStored;193 var container = document.createElement('div');194 var options = {195 container: container,196 paymentMethod: paymentMethod,197 isStored: isStored,198 path: path,199 description: description,200 paymentMethodID: paymentMethodID,201 isSchemeNotStored: isSchemeNotStored202 };203 var imagePath = getImagePath(options);204 var liContents = getListContents(_objectSpread(_objectSpread({}, options), {}, {205 imagePath: imagePath206 }));207 li.innerHTML = liContents;208 li.classList.add('paymentMethod');209 handlePayment(options);210 configureContainer(options);211 li.append(container);212 paymentMethodsUI.append(li);213 var node = (_store$componentsObj$2 = store.componentsObj[paymentMethodID]) === null || _store$componentsObj$2 === void 0 ? void 0 : _store$componentsObj$2.node;214 if (node) {215 node.mount(container);216 }217 if (paymentMethodID === 'giropay') {218 container.innerHTML = '';219 }220 handleInput(options);221 setValid(options);...

Full Screen

Full Screen

gsSuspendedTab.js

Source:gsSuspendedTab.js Github

copy

Full Screen

1/*global tgs, gsFavicon, gsStorage, gsSession, gsUtils, gsIndexedDb */2// eslint-disable-next-line no-unused-vars3var gsSuspendedTab = (function() {4 'use strict';5 async function initTab(tab, tabView, { quickInit }) {6 if (!tabView) {7 gsUtils.warning(8 tab.id,9 'Could not get internalTabView for suspended tab'10 );11 }12 const suspendedUrl = tab.url;13 // Set sessionId for subsequent checks14 tabView.document.sessionId = gsSession.getSessionId();15 // Set title16 let title = gsUtils.getSuspendedTitle(suspendedUrl);17 if (title.indexOf('<') >= 0) {18 // Encode any raw html tags that might be used in the title19 title = gsUtils.htmlEncode(title);20 }21 setTitle(tabView.document, title);22 // Set faviconMeta23 const faviconMeta = await gsFavicon.getFaviconMetaData(tab);24 setFaviconMeta(tabView.document, faviconMeta);25 if (quickInit) {26 return;27 }28 gsUtils.localiseHtml(tabView.document);29 const options = gsStorage.getSettings();30 const originalUrl = gsUtils.getOriginalUrl(suspendedUrl);31 // Add event listeners32 setUnloadTabHandler(tabView.window, tab);33 setUnsuspendTabHandlers(tabView.document, tab);34 // Set imagePreview35 const previewMode = options[gsStorage.SCREEN_CAPTURE];36 const previewUri = await getPreviewUri(suspendedUrl);37 await toggleImagePreviewVisibility(38 tabView.document,39 tab,40 previewMode,41 previewUri42 );43 // Set theme44 const theme = options[gsStorage.THEME];45 const isLowContrastFavicon = faviconMeta.isDark;46 setTheme(tabView.document, theme, isLowContrastFavicon);47 // Set command48 const suspensionToggleHotkey = await tgs.getSuspensionToggleHotkey();49 setCommand(tabView.document, suspensionToggleHotkey);50 // Set url51 setUrl(tabView.document, originalUrl);52 // Set reason53 const suspendReasonInt = tgs.getTabStatePropForTabId(54 tab.id,55 tgs.STATE_SUSPEND_REASON56 );57 let suspendReason = null;58 if (suspendReasonInt === 3) {59 suspendReason = chrome.i18n.getMessage('js_suspended_low_memory');60 }61 setReason(tabView.document, suspendReason);62 // Show the view63 showContents(tabView.document);64 // Set scrollPosition (must come after showing page contents)65 const scrollPosition = gsUtils.getSuspendedScrollPosition(suspendedUrl);66 setScrollPosition(tabView.document, scrollPosition, previewMode);67 tgs.setTabStatePropForTabId(tab.id, tgs.STATE_SCROLL_POS, scrollPosition);68 // const whitelisted = gsUtils.checkWhiteList(originalUrl);69 }70 function showNoConnectivityMessage(tabView) {71 if (!tabView.document.getElementById('disconnectedNotice')) {72 loadToastTemplate(tabView.document);73 }74 tabView.document.getElementById('disconnectedNotice').style.display =75 'none';76 setTimeout(function() {77 tabView.document.getElementById('disconnectedNotice').style.display =78 'block';79 }, 50);80 }81 function updateCommand(tabView, suspensionToggleHotkey) {82 setCommand(tabView.document, suspensionToggleHotkey);83 }84 function updateTheme(tabView, tab, theme, isLowContrastFavicon) {85 setTheme(tabView.document, theme, isLowContrastFavicon);86 }87 async function updatePreviewMode(tabView, tab, previewMode) {88 const previewUri = await getPreviewUri(tab.url);89 await toggleImagePreviewVisibility(90 tabView.document,91 tab,92 previewMode,93 previewUri94 );95 const scrollPosition = gsUtils.getSuspendedScrollPosition(tab.url);96 setScrollPosition(tabView.document, scrollPosition, previewMode);97 }98 function showContents(_document) {99 _document.querySelector('body').classList.remove('hide-initially');100 }101 function setScrollPosition(_document, scrollPosition, previewMode) {102 const scrollPosAsInt = (scrollPosition && parseInt(scrollPosition)) || 0;103 const scrollImagePreview = previewMode === '2';104 if (scrollImagePreview && scrollPosAsInt > 15) {105 const offsetScrollPosition = scrollPosAsInt + 151;106 _document.body.scrollTop = offsetScrollPosition;107 _document.documentElement.scrollTop = offsetScrollPosition;108 } else {109 _document.body.scrollTop = 0;110 _document.documentElement.scrollTop = 0;111 }112 }113 function setTitle(_document, title) {114 _document.title = title;115 _document.getElementById('gsTitle').innerHTML = title;116 _document.getElementById('gsTopBarTitle').innerHTML = title;117 // Prevent unsuspend by parent container118 // Using mousedown event otherwise click can still be triggered if119 // mouse is released outside of this element120 _document.getElementById('gsTopBarTitle').onmousedown = function(e) {121 e.stopPropagation();122 };123 }124 function setUrl(_document, url) {125 _document.getElementById('gsTopBarUrl').innerHTML = cleanUrl(url);126 _document.getElementById('gsTopBarUrl').setAttribute('href', url);127 _document.getElementById('gsTopBarUrl').onmousedown = function(e) {128 e.stopPropagation();129 };130 }131 function setFaviconMeta(_document, faviconMeta) {132 _document133 .getElementById('gsTopBarImg')134 .setAttribute('src', faviconMeta.normalisedDataUrl);135 _document136 .getElementById('gsFavicon')137 .setAttribute('href', faviconMeta.transparentDataUrl);138 }139 function setTheme(_document, theme, isLowContrastFavicon) {140 if (theme === 'dark') {141 _document.querySelector('body').classList.add('dark');142 } else {143 _document.querySelector('body').classList.remove('dark');144 }145 if (theme === 'dark' && isLowContrastFavicon) {146 _document147 .getElementById('faviconWrap')148 .classList.add('faviconWrapLowContrast');149 } else {150 _document151 .getElementById('faviconWrap')152 .classList.remove('faviconWrapLowContrast');153 }154 }155 function setReason(_document, reason) {156 let reasonMsgEl = _document.getElementById('reasonMsg');157 if (!reasonMsgEl) {158 reasonMsgEl = _document.createElement('div');159 reasonMsgEl.setAttribute('id', 'reasonMsg');160 reasonMsgEl.classList.add('reasonMsg');161 const containerEl = _document.getElementById('suspendedMsg-instr');162 containerEl.insertBefore(reasonMsgEl, containerEl.firstChild);163 }164 reasonMsgEl.innerHTML = reason;165 }166 async function getPreviewUri(suspendedUrl) {167 const originalUrl = gsUtils.getOriginalUrl(suspendedUrl);168 const preview = await gsIndexedDb.fetchPreviewImage(originalUrl);169 let previewUri = null;170 if (171 preview &&172 preview.img &&173 preview.img !== null &&174 preview.img !== 'data:,' &&175 preview.img.length > 10000176 ) {177 previewUri = preview.img;178 }179 return previewUri;180 }181 function buildImagePreview(_document, tab, previewUri) {182 return new Promise(resolve => {183 const previewEl = _document.createElement('div');184 const bodyEl = _document.getElementsByTagName('body')[0];185 previewEl.setAttribute('id', 'gsPreviewContainer');186 previewEl.classList.add('gsPreviewContainer');187 previewEl.innerHTML = _document.getElementById(188 'previewTemplate'189 ).innerHTML;190 const unsuspendTabHandler = buildUnsuspendTabHandler(_document, tab);191 previewEl.onclick = unsuspendTabHandler;192 gsUtils.localiseHtml(previewEl);193 bodyEl.appendChild(previewEl);194 const previewImgEl = _document.getElementById('gsPreviewImg');195 const onLoadedHandler = function() {196 previewImgEl.removeEventListener('load', onLoadedHandler);197 previewImgEl.removeEventListener('error', onLoadedHandler);198 resolve();199 };200 previewImgEl.setAttribute('src', previewUri);201 previewImgEl.addEventListener('load', onLoadedHandler);202 previewImgEl.addEventListener('error', onLoadedHandler);203 });204 }205 function addWatermarkHandler(_document) {206 _document.querySelector('.watermark').onclick = () => {207 chrome.tabs.create({ url: chrome.extension.getURL('about.html') });208 };209 }210 async function toggleImagePreviewVisibility(211 _document,212 tab,213 previewMode,214 previewUri215 ) {216 const builtImagePreview =217 _document.getElementById('gsPreviewContainer') !== null;218 if (219 !builtImagePreview &&220 previewUri &&221 previewMode &&222 previewMode !== '0'223 ) {224 await buildImagePreview(_document, tab, previewUri);225 } else {226 addWatermarkHandler(_document);227 }228 if (!_document.getElementById('gsPreviewContainer')) {229 return;230 }231 const overflow = previewMode === '2' ? 'auto' : 'hidden';232 _document.body.style['overflow'] = overflow;233 if (previewMode === '0' || !previewUri) {234 _document.getElementById('gsPreviewContainer').style.display = 'none';235 _document.getElementById('suspendedMsg').style.display = 'flex';236 _document.body.classList.remove('img-preview-mode');237 } else {238 _document.getElementById('gsPreviewContainer').style.display = 'block';239 _document.getElementById('suspendedMsg').style.display = 'none';240 _document.body.classList.add('img-preview-mode');241 }242 }243 function setCommand(_document, command) {244 const hotkeyEl = _document.getElementById('hotkeyWrapper');245 if (command) {246 hotkeyEl.innerHTML =247 '<span class="hotkeyCommand">(' + command + ')</span>';248 } else {249 const reloadString = chrome.i18n.getMessage(250 'js_suspended_hotkey_to_reload'251 );252 hotkeyEl.innerHTML = `<a id="setKeyboardShortcut" href="#">${reloadString}</a>`;253 }254 }255 function setUnloadTabHandler(_window, tab) {256 // beforeunload event will get fired if: the tab is refreshed, the url is changed,257 // the tab is closed, or the tab is frozen by chrome ??258 // when this happens the STATE_UNLOADED_URL gets set with the suspended tab url259 // if the tab is refreshed, then on reload the url will match and the tab will unsuspend260 // if the url is changed then on reload the url will not match261 // if the tab is closed, the reload will never occur262 _window.addEventListener('beforeunload', function(e) {263 gsUtils.log(tab.id, 'BeforeUnload triggered: ' + tab.url);264 if (tgs.isCurrentFocusedTab(tab)) {265 tgs.setTabStatePropForTabId(tab.id, tgs.STATE_UNLOADED_URL, tab.url);266 } else {267 gsUtils.log(268 tab.id,269 'Ignoring beforeUnload as tab is not currently focused.'270 );271 }272 });273 }274 function setUnsuspendTabHandlers(_document, tab) {275 const unsuspendTabHandler = buildUnsuspendTabHandler(_document, tab);276 _document.getElementById('gsTopBarUrl').onclick = unsuspendTabHandler;277 _document.getElementById('gsTopBar').onmousedown = unsuspendTabHandler;278 _document.getElementById('suspendedMsg').onclick = unsuspendTabHandler;279 }280 function buildUnsuspendTabHandler(_document, tab) {281 return function(e) {282 e.preventDefault();283 e.stopPropagation();284 if (e.target.id === 'setKeyboardShortcut') {285 chrome.tabs.create({ url: 'chrome://extensions/shortcuts' });286 } else if (e.which === 1) {287 showUnsuspendAnimation(_document);288 tgs.unsuspendTab(tab);289 }290 };291 }292 function showUnsuspendAnimation(_document) {293 if (_document.body.classList.contains('img-preview-mode')) {294 _document.getElementById('refreshSpinner').classList.add('spinner');295 } else {296 _document.body.classList.add('waking');297 _document.getElementById('snoozyImg').src = chrome.extension.getURL(298 'img/snoozy_tab_awake.svg'299 );300 _document.getElementById('snoozySpinner').classList.add('spinner');301 }302 }303 function loadToastTemplate(_document) {304 const toastEl = _document.createElement('div');305 toastEl.setAttribute('id', 'disconnectedNotice');306 toastEl.classList.add('toast-wrapper');307 toastEl.innerHTML = _document.getElementById('toastTemplate').innerHTML;308 gsUtils.localiseHtml(toastEl);309 _document.getElementsByTagName('body')[0].appendChild(toastEl);310 }311 function cleanUrl(urlStr) {312 // remove scheme313 if (urlStr.indexOf('//') > 0) {314 urlStr = urlStr.substring(urlStr.indexOf('//') + 2);315 }316 // remove query string317 let match = urlStr.match(/\/?[?#]+/);318 if (match) {319 urlStr = urlStr.substring(0, match.index);320 }321 // remove trailing slash322 match = urlStr.match(/\/$/);323 if (match) {324 urlStr = urlStr.substring(0, match.index);325 }326 return urlStr;327 }328 return {329 initTab,330 showNoConnectivityMessage,331 updateCommand,332 updateTheme,333 updatePreviewMode,334 };...

Full Screen

Full Screen

calendar-event-dialog.js

Source:calendar-event-dialog.js Github

copy

Full Screen

1/* ***** BEGIN LICENSE BLOCK *****2 * Version: GPL 3.03 *4 * The contents of this file are subject to the General Public License5 * 3.0 (the "License"); you may not use this file except in compliance with6 * the License. You may obtain a copy of the License at7 * http://www.gnu.org/licenses/gpl.html8 *9 * Software distributed under the License is distributed on an "AS IS" basis,10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License11 * for the specific language governing rights and limitations under the12 * License.13 *14 * -- Exchange 2007/2010 Calendar and Tasks Provider.15 * -- For Thunderbird with the Lightning add-on.16 *17 * Author: Michel Verbraak (info@1st-setup.nl)18 * Website: http://www.1st-setup.nl/wordpress/?page_id=13319 * email: exchangecalendar@extensions.1st-setup.nl20 *21 *22 * This code uses parts of the Microsoft Exchange Calendar Provider code on which the23 * "Exchange Data Provider for Lightning" was based.24 * The Initial Developer of the Microsoft Exchange Calendar Provider Code is25 * Andrea Bittau <a.bittau@cs.ucl.ac.uk>, University College London26 * Portions created by the Initial Developer are Copyright (C) 200927 * the Initial Developer. All Rights Reserved.28 *29 * ***** BEGIN LICENSE BLOCK *****/30var Cu = Components.utils;31var Ci = Components.interfaces;32var Cc = Components.classes;33Cu.import("resource://calendar/modules/calUtils.jsm");34Cu.import("resource://gre/modules/Services.jsm");35function exchEventDialog(aDocument, aWindow)36{37 this._document = aDocument;38 this._window = aWindow;39 this.globalFunctions = Cc["@1st-setup.nl/global/functions;1"]40 .getService(Ci.mivFunctions);41}42exchEventDialog.prototype = {43 _initialized: false,44 _oldCallback: null,45 onAcceptCallback: function _onAcceptCallback(aItem, aCalendar, aOriginalItem, aIsClosing)46 {47 if ((cal.isEvent(aItem)) && (aCalendar.type == "exchangecalendar")) {48 if (!aItem.className) {49 var newItem = Cc["@1st-setup.nl/exchange/calendarevent;1"]50 .createInstance(Ci.mivExchangeEvent);51 newItem.cloneToCalEvent(aItem);52 aItem = newItem;53 }54 }55 if ((!cal.isEvent(aItem)) && (aCalendar.type == "exchangecalendar")) {56 // Save extra exchange fields to item.57 if (!aItem.className) {58 var newItem = Cc["@1st-setup.nl/exchange/calendartodo;1"]59 .createInstance(Ci.mivExchangeTodo);60 newItem.cloneToCalEvent(aItem);61 aItem = newItem;62 }63 aItem.totalWork = this._document.getElementById("exchWebService-totalWork-count").value;64 aItem.actualWork = this._document.getElementById("exchWebService-actualWork-count").value;65 aItem.mileage = this._document.getElementById("exchWebService-mileage-count").value;66 aItem.billingInformation = this._document.getElementById("exchWebService-billingInformation-count").value;67 aItem.companies = this._document.getElementById("exchWebService-companies-count").value;68 }69try{70 if (this.newItem) {71 aItem.bodyType = "HTML";72 aItem.body = this._document.getElementById("exchWebService-body-editor").content;73 }74 else {75 if (aItem.bodyType == "HTML") {76 aItem.body = this._document.getElementById("exchWebService-body-editor").content;77 }78 }79}catch(err){dump("Error saving content\n");}80 if (this._oldCallback) {81 this._oldCallback(aItem, aCalendar, aOriginalItem, aIsClosing);82 }83 },84 onLoad: function _onLoad()85 {86 //onLoad();87 if (this._window.arguments[0].calendarEvent.calendar.type != "exchangecalendar") {88 if (this._document.getElementById("item-description")) {89 this._document.getElementById("item-description").hidden = false;90 }91 if (this._document.getElementById("exchWebService-body-editor")) {92 this._document.getElementById("exchWebService-body-editor").hidden = true;93 }94 return;95 }96 if (this._initialized) return;97 this._oldCallback = this._window.onAcceptCallback;98 var self = this;99 this._window.onAcceptCallback = function(aItem, aCalendar, aOriginalItem, aIsClosing) { self.onAcceptCallback(aItem, aCalendar, aOriginalItem, aIsClosing); };100 if (this._document.getElementById("todo-entrydate")) {101 this._initialized = true;102 var args = this._window.arguments[0];103 var item = args.calendarEvent;104 this.updateScreen(item, item.calendar);105 //Cc["@mozilla.org/consoleservice;1"]106 // .getService(Ci.nsIConsoleService).logStringMessage(item.exchangeXML);107//dump("event.dialog: item.exchangeXML:"+item.exchangeXML+"\n");108 if ((item.bodyType == "HTML") || (item.bodyType === undefined)) {109 if (this._document.getElementById("item-description")) {110 this._document.getElementById("item-description").hidden = true;111 }112 if (this._document.getElementById("exchWebService-body-editor")) {113 this._document.getElementById("exchWebService-body-editor").hidden = false;114 if (item.bodyType !== undefined) {115 this._document.getElementById("exchWebService-body-editor").content = item.body;116 }117 else {118 this.newItem = true;119 if (item.body) {120 if ((item.body.indexOf("<BODY>") > -1) || (item.body.indexOf("<body>") > -1)) {121 this._document.getElementById("exchWebService-body-editor").content = item.body;122 }123 else {124 this._document.getElementById("exchWebService-body-editor").content = this.globalFunctions.fromText2HTML(item.getProperty("DESCRIPTION"));125 }126 }127 else {128 this._document.getElementById("exchWebService-body-editor").content = this.globalFunctions.fromText2HTML(item.getProperty("DESCRIPTION"));129 }130 }131 }132 }133 else {134 if (this._document.getElementById("item-description")) {135 this._document.getElementById("item-description").hidden = false;136 }137 if (this._document.getElementById("exchWebService-body-editor")) {138 this._document.getElementById("exchWebService-body-editor").hidden = true;139 }140 }141 }142 },143 updateScreen: function _updateScreen(aItem, aCalendar)144 {145 var item = aItem;146 if ((!cal.isEvent(item)) && (aCalendar.type == "exchangecalendar")) {147 var ownerLabel = this._document.getElementById("exchWebService-owner-label");148 if (ownerLabel) {149 ownerLabel.value = item.owner;150 }151 try {152 this._document.getElementById("exchWebService-details-row1").removeAttribute("collapsed");153 this._document.getElementById("exchWebService-details-row2").removeAttribute("collapsed");154 this._document.getElementById("exchWebService-details-row3").removeAttribute("collapsed");155 }156 catch (ex) {}157 this._document.getElementById("exchWebService-owner-row").setAttribute("collapsed", "false");158 this._document.getElementById("exchWebService-details-separator").hidden = false;159 if (item.className) {160 this._document.getElementById("exchWebService-totalWork-count").value = item.totalWork;161 this._document.getElementById("exchWebService-actualWork-count").value = item.actualWork;162 this._document.getElementById("exchWebService-mileage-count").value = item.mileage;163 this._document.getElementById("exchWebService-billingInformation-count").value = item.billingInformation;164 this._document.getElementById("exchWebService-companies-count").value = item.companies;165 }166 this._document.getElementById("event-grid-location-row").hidden = true;167 // Clear reminder select list for todo168 this._document.getElementById("reminder-none-separator").hidden = true;169 this._document.getElementById("reminder-0minutes-menuitem").hidden = true;170 this._document.getElementById("reminder-5minutes-menuitem").hidden = true;171 this._document.getElementById("reminder-15minutes-menuitem").hidden = true;172 this._document.getElementById("reminder-30minutes-menuitem").hidden = true;173 this._document.getElementById("reminder-minutes-separator").hidden = true;174 this._document.getElementById("reminder-1hour-menuitem").hidden = true;175 this._document.getElementById("reminder-2hours-menuitem").hidden = true;176 this._document.getElementById("reminder-12hours-menuitem").hidden = true;177 this._document.getElementById("reminder-hours-separator").hidden = true;178 this._document.getElementById("reminder-1day-menuitem").hidden = true;179 this._document.getElementById("reminder-2days-menuitem").hidden = true;180 this._document.getElementById("reminder-1week-menuitem").hidden = true;181 182 this._document.getElementById("timezone-starttime").hidden = true;183 this._document.getElementById("timezone-endtime").hidden = true;184 if (this._document.getElementById("item-repeat")) {185 this._document.getElementById("item-repeat").addEventListener("command", function() { self.updateRepeat(); }, false);186 }187 //this.updateTime();188 this.updateRepeat();189 }190 else {191 try {192 this._document.getElementById("exchWebService-details-row1").setAttribute("collapsed", "true");193 this._document.getElementById("exchWebService-details-row2").setAttribute("collapsed", "true");194 this._document.getElementById("exchWebService-details-row3").setAttribute("collapsed", "true");195 }196 catch (ex) {}197 this._document.getElementById("exchWebService-owner-row").setAttribute("collapsed", "true");198 this._document.getElementById("exchWebService-details-separator").hidden = true;199 this._document.getElementById("event-grid-location-row").hidden = false;200 // Clear reminder select list for todo201 this._document.getElementById("reminder-none-separator").hidden = false;202 this._document.getElementById("reminder-0minutes-menuitem").hidden = false;203 this._document.getElementById("reminder-5minutes-menuitem").hidden = false;204 this._document.getElementById("reminder-15minutes-menuitem").hidden = false;205 this._document.getElementById("reminder-30minutes-menuitem").hidden = false;206 this._document.getElementById("reminder-minutes-separator").hidden = false;207 this._document.getElementById("reminder-1hour-menuitem").hidden = false;208 this._document.getElementById("reminder-2hours-menuitem").hidden = false;209 this._document.getElementById("reminder-12hours-menuitem").hidden = false;210 this._document.getElementById("reminder-hours-separator").hidden = false;211 this._document.getElementById("reminder-1day-menuitem").hidden = false;212 this._document.getElementById("reminder-2days-menuitem").hidden = false;213 this._document.getElementById("reminder-1week-menuitem").hidden = false;214 this._document.getElementById("timezone-starttime").hidden = false;215 this._document.getElementById("timezone-endtime").hidden = false;216 }217 },218 // This will remove the time value from the repeat part and tooltip.219 updateRepeat: function _updateRepeat()220 {221 var repeatDetails = this._document.getElementById("repeat-details").childNodes;222 if (repeatDetails.length == 3) {223 this._document.getElementById("repeat-details").removeChild(repeatDetails[2]);224 var toolTip = repeatDetails[0].getAttribute("tooltiptext");225 var tmpArray = toolTip.split("\n");226 tmpArray.splice(2,1);227 repeatDetails[0].setAttribute("tooltiptext", tmpArray.join("\n"));228 repeatDetails[1].setAttribute("tooltiptext", tmpArray.join("\n"));229 }230 },231 selectedCalendarChanged: function _selectedCalendarChanged(aMenuList)232 {233 updateCalendar();234 this.updateScreen(this._window.calendarItem, getCurrentCalendar());235 },236}237var tmpEventDialog = new exchEventDialog(document, window);...

Full Screen

Full Screen

area.js

Source:area.js Github

copy

Full Screen

1/*2 * ------------------------------------------3 * 富媒体编辑器输入区封装实现文件4 * @version 1.05 * @author genify(caijf@corp.netease.com)6 * ------------------------------------------7 */8var f = function(){9 var _ = NEJ.P,10 _o = NEJ.O,11 _v = _('nej.v'),12 _e = _('nej.e'),13 _u = _('nej.u'),14 _h = _('nej.h'),15 _p = _('nej.ut'),16 _pro;17 if (!!_p._$$EditorArea) return;18 /**19 * 富媒体编辑器输入区封装20 * @class {nej.ut._$$EditorArea} 富媒体编辑器输入区封装21 * @extends {nej.ut._$$Event}22 * @param {Object} _options 可选配置参数,已处理参数列表如下23 * @config {Node|String|Function} parent 父节点或者编辑器加入父节点执行函数24 * @config {String} style 编辑器初始样式25 * @config {Boolean} focus 是否自动聚焦26 * @config {String} content 文本内容27 * 28 * [hr]29 * 30 * @event {onselectionchange}31 */32 _p._$$EditorArea = NEJ.C();33 _pro = _p._$$EditorArea._$extend(_p._$$Event);34 /**35 * 控件初始化36 * @protected37 * @method {__init}38 * @return {Void}39 */40 _pro.__init = function(){41 this.__fopt = {42 visible:!0,43 onload:this.__onIFrameLoaded._$bind(this)44 };45 this.__supInit();46 };47 /**48 * 控件重置49 * @protected50 * @method {__reset}51 * @param {Object} 可选配置参数52 * @return {Void}53 */54 _pro.__reset = (function(){55 var _cnttpl = '<head><base href="#<BSUL>"/><style>html,body{margin:0;padding:0;border:0;cursor:text;font-size:14px;font-family:Arial;word-wrap:break-word;}#<UDCS></style></head><body contenteditable="true"></body>';56 return function(_options){57 this.__supReset(_options);58 this.__focus = !!_options.focus;59 this.__content = _cnttpl60 .replace('#<UDCS>',_options.style||'')61 .replace('#<BSUL>',_options.base||location.href);62 this.__initcnt = _options.content||'';63 this.__fopt.parent = 64 _e._$get(_options.parent)||document.body;65 this.__iframe = _e._$createXFrame(this.__fopt);66 };67 })();68 /**69 * 控件销毁70 * @protected71 * @method {__destroy}72 * @return {Void}73 */74 _pro.__destroy = function(){75 this.__supDestroy();76 _h.__clearRange(this._$getDocument());77 delete this.__content;78 delete this.__fopt.parent;79 delete this.__initcnt;80 this.__iframe = _e._$remove(this.__iframe);81 };82 /**83 * 保存选中状态84 * @protected85 * @method {__doSaveRange}86 * @return {Void}87 */88 _pro.__doSaveRange = function(){89 _h.__saveRange(this._$getDocument());90 };91 /**92 * iframe载入完成触发事件93 * @protected94 * @method {__onIFrameLoaded}95 * @return {Void}96 */97 _pro.__onIFrameLoaded = function(_iframe){98 var _document = this._$getDocument();99 _document.open();100 _document.write(this.__content);101 if (location.hostname!=document.domain)102 _document.domain = document.domain;103 _document.close(); // <- will trigger iframe onload104 this.__doInitDomEvent([[105 _document,'click',106 this.__onDocumentClick._$bind(this)107 ],[108 _document,'selectionchange',109 this.__onSelectionChange._$bind(this)110 ],[111 _document,'beforedeactivate',112 this.__doSaveRange._$bind(this)113 ],[114 _document,'keydown',115 this.__onInputCheck._$bind(this)116 ],[117 _document,'mouseup',118 this.__onInputCheck._$bind(this)119 ],[120 _document,'paste',121 this.__onInputCheck._$bind(this)122 ],[123 _document,'drop',124 this.__onInputCheck._$bind(this)125 ]]);126 // init content and focus127 if (!!this.__initcnt){128 this._$setContent(this.__initcnt);129 }130 if (this.__focus){131 this._$focus();132 delete this.__focus;133 }134 };135 /**136 * 文档点击事件137 * @protected138 * @method {__onDocumentClick}139 * @param {Event} 事件对象140 * @return {Void}141 */142 _pro.__onDocumentClick = function(_event){143 _v._$dispatchEvent(document,'click');144 };145 /**146 * 选中内容变化触发事件147 * @protected148 * @method {__onSelectionChange}149 * @return {Void}150 */151 _pro.__onSelectionChange = function(){152 // TODO something153 this._$dispatchEvent('onselectionchange');154 };155 /**156 * 输入事件157 * @return {[type]} [description]158 */159 _pro.__onInputCheck = function(){160 if (!!this.__timer){161 window.clearTimeout(this.__timer);162 }163 this.__timer = window.setTimeout(164 this.__doCompareContent._$bind(this),100165 );166 };167 /**168 * 比较富文本的内容169 * @return {[type]} [description]170 */171 _pro.__doCompareContent = function(){172 var _document = this._$getDocument();173 if (!_document) return;174 var _content = _document.body.innerHTML;175 if (this.__initcnt!=_content){176 this.__initcnt = _content;177 this._$dispatchEvent('oninput',{178 cont:this._$getContent(),179 txt:this._$getTextContent()180 });181 }182 };183 /**184 * 聚焦编辑器185 * @method {_$focus}186 * @param {Number} 光标位置,默认为0,0-末尾、1-起始、2-不变187 * @return {nej.ut._$$EditorArea}188 */189 _pro._$focus = function(_cursor){190 var _document = this._$getDocument();191 if (!_document) return this;192 _h.__focusRange(_document.body);193 _h.__moveCursorPosition(194 _document.body,195 parseInt(_cursor)||0196 );197 this.__onSelectionChange();198 return this;199 };200 /**201 * 取编辑器文档对象202 * @method {_$getDocument}203 * @return {Node} 文档对象204 */205 _pro._$getDocument = function(){206 return this.__iframe.contentWindow.document;207 };208 /**209 * 取编辑内容210 * @method {_$getContent}211 * @return {String} 内容212 */213 _pro._$getContent = function(_filter){214 var _document = this._$getDocument();215 _html = _h.__filterContent(!_document?'':_document.body.innerHTML);216 if(!_filter){217 _html = _h.__filterContentStyle(_html);218 }219 return !_h.__filterWordContent?_html:_h.__filterWordContent(_html);220 };221 /**222 * 取纯文本的编辑内容223 * @method {_$getTextContent}224 * @return {String} 内容225 */226 _pro._$getTextContent = function(){227 var _document = this._$getDocument(),228 _text = _document.body.innerText||229 _document.body.textContent;230 return !_document?'':_text;231 };232 /**233 * 设置内容234 * @method {_$setContent}235 * @param {String} 编辑内容236 * @return {nej.ut._$$EditorArea}237 */238 _pro._$setContent = function(_content){239 var _document = this._$getDocument();240 if (!_document) return this;241 _document.body.innerHTML = _content;242 this.__onInputCheck();243 return this;244 };245 /**246 * 执行编辑命令247 * @method {_$execCommand}248 * @param {String} 命令名称249 * @param {String} 命令值250 * @param {String} 是否通过style的方式来改变样式,比如superscript命令251 * @return {nej.ut._$$EditorArea}252 */253 _pro._$execCommand = function(_command,_value,_css){254 var _document = this._$getDocument();255 if (!_document) return this;256 _h.__execCommand(_document,'styleWithCSS',false);257 _h.__execCommand(_document,_command,_value);258 this._$focus(2);259 this.__onInputCheck();260 return this;261 };262 /**263 * 查询命令的状态264 * @method {_$queryCommand}265 * @param {String} 命令名称266 * @param {String} 查询类型,State/Enabled/Value267 * @return {Variable} 查询结果268 */269 _pro._$queryCommand = function(_command,_type){270 var _document = this._$getDocument();271 return !_document ? null272 :_document['queryCommand'+_type](_command);273 };274 /**275 * 获取选中内容的文本276 * @method {_$getSelectText}277 * @return {String} 文本内容278 */279 _pro._$getSelectText = function(){280 this._$focus(2);281 return _h.__getSelectText(this._$getDocument());282 };283 /**284 * 获取选择内容的HTML285 * @method {_$getSelectHtml}286 * @return {String} HTML代码287 */288 _pro._$getSelectHtml = function(){289 this._$focus(2);290 return _h.__getSelectHtml(this._$getDocument());291 };292 /**293 * 取编辑区域容器位置大小信息294 * @return {Object} 位置大小信息295 * [ntb]296 * scrollTop | 滚动垂直偏移297 * scrollLeft | 滚动水平偏移298 * clientWidth | 页面可视宽度299 * clientHeight | 页面可视高度300 * scrollWidth | 页面滚动宽度301 * scrollHeight | 页面滚动高度302 * [/ntb]303 */304 _pro._$getAreaBox = function(){305 var _document = this._$getDocument();306 return !_document?null:_e._$getPageBox(_document);307 };308};309NEJ.define(310 '{lib}util/editor/area.js',[311 '{lib}util/event.js',312 '{patch}editor.js' ...

Full Screen

Full Screen

editor.js

Source:editor.js Github

copy

Full Screen

1/**2 * ------------------------------------------3 * 富文本编辑器接口实现文件4 * @version 1.05 * @author genify(caijf@corp.netease.com)6 * ------------------------------------------7 */8NEJ.define([9 'base/element',10 'base/platform'11],function(_e,_m,_p,_o,_f,_r){12 var __empty = /(?:<(p|div)>(?:\&nbsp\;|<br\/?>)<\/\1>|<br\/?>|\&nbsp\;|\s)+$/gi, // empty content13 __reg_cls0 = /(?:class|lang)="(mso)?[^"]*"/gi,14 __reg_cls1 = /(?:class|lang)='(mso)?[^']*'/gi,15 __reg_cls2 = /(?:class|lang)=(mso)?[^>\s]*/gi,// IE7/8 hack16 __reg_ccm = /(?:<!--)[^>]*(?:-->)/gi,17 __reg_st0 = /(?:<[^>]* style)="([^"]*)"/gi,18 __reg_st1 = /(?:<[^>]* style)='([^']*)'/gi,19 __reg_st2 = /(?:<[^>]* style)=([^>\s]*)/gi,// IE7/8 hack20 __reg_bgc = /(?:background-color:|text-align:|color:)([^;]*)(;)*/gi;//clear class,lang21 /**22 * 取节点所在的窗体对象23 * @param {Node} _node 节点24 * @return {Window} 窗体25 */26 _p.__getWindow = function(_node){27 var _document = _p.__getDocument(_node);28 return _document.defaultView||_document.parentWindow||_document.window||_document;29 };30 /**31 * 取节点关联的文档对象32 * @param {Node} _node 节点33 * @return {Document} 文档对象34 */35 _p.__getDocument = function(_node){36 return _node.ownerDocument||_node;37 };38 /**39 * 取选择区对象40 * @param {Window} _window 窗体对象41 * @return {DOMSelection} 选择区对象42 */43 _p.__getSelection = function(_window){44 if (!!_window.getSelection)45 return _window.getSelection();46 var _document = _window.document;47 if (!!_document.getSelection)48 return _document.getSelection();49 if (!!_document.selection)50 return _document.selection;51 return null;52 };53 /**54 * 取选择区范围操作对象55 * @param {Window} _window 窗体对象56 * @return {Range} 范围操作对象57 */58 _p.__getRange = function(_window){59 _window = _p.__getWindow(_window);60 var _selection = _p.__getSelection(_window);61 if (!_selection)62 return null;63 if (!!_selection.getRangeAt){64 return _selection.getRangeAt(0);65 }66 if (!!_selection.createRange)67 return _selection.createRange();68 return null;69 };70 /**71 * 获取选中内容的文本72 * @return {String} 文本内容73 */74 _p.__getSelectText = function(_document){75 var _range = this.__getRange(_document);76 if (!_range) return '';77 return _range.toString()||_range.cloneContents().textContent||_range.commonAncestorContainer.data;78 };79 /**80 * 获取选中内容的html81 * @param {Object} _document82 * @return {String} 选中内容的html83 */84 _p.__getSelectHtml = function(_document){85 var _range = this.__getRange(_document);86 if (!_range) return '';87 var _ntmp = _e._$create('div');88 _ntmp.appendChild(_range.cloneContents());89 return _ntmp.innerHTML;90 };91 /**92 * 获取选中内容的父节点93 * @param {Object} _document94 * @return {Node|String} 选中内容的父节点95 */96 _p.__getSelectNode = (function(){97 var _checkNodeType = function(_node){98 if (_node.nodeType == 1){99 return _node;100 }else{101 _node = _node.parentNode;102 return _checkNodeType(_node);103 }104 };105 return function(_document){106 var _range = this.__getRange(_document),107 _node = _range.commonAncestorContainer||_range.parentElement();108 if (!_range || !_node) return '';109 return _checkNodeType(_node);110 };111 })();112 /**113 * 保存当前选择状态114 * @param {Node} _node 节点115 * @return {Range} 范围116 */117 _p.__saveRange = function(_node){118 // do nothing119 };120 /**121 * 聚焦至选中区域122 * @param {Node} _node 节点123 * @return {Void}124 */125 _p.__focusRange = function(_node){126 _node.focus();127 };128 /**129 * 清除选择状态130 * @param {Node} _node 节点131 * @return {Void}132 */133 _p.__clearRange = function(_node){134 // do nothing135 };136 /**137 * FF支持selectionchange138 * @param {[type]} _document [description]139 * @return {[type]} [description]140 */141 _p.__supportSelectionChange = function(_document){142 // do nothing143 };144 /**145 * 移动光标至节点的指定位置146 * @param {Node} _node 节点147 * @param {Number} _position 位置,0-末尾、1-起始148 * @return {Void}149 */150 _p.__moveCursorPosition = (function(){151 var _fmap = [function(_node){return _node.childNodes.length;}152 ,function(){return 0;}];153 return function(_node,_position){154 var _func = _fmap[_position];155 if (!_func){156 return;157 }158 _p.__getSelection(_p.__getWindow(_node))159 .collapse(_node,_func(_node));160 };161 })();162 /**163 * 执行编辑命令164 * @param {Node} _document 文档对象165 * @param {String} _command 命令名称166 * @param {String} _value 命令值167 * @return {Void}168 */169 _p.__execCommand = function(_document,_command,_value){170 if(_command == 'inserthtml'){171 this.__insertHtml(_document,_value);172 return;173 }174 _document.execCommand(_command,!1,_value);175 };176 /**177 * 插入html命令处理178 * @param {Object} _document 文档对象179 * @param {Object} _html180 */181 _p.__insertHtml = function(_document,_html){182 if (!document.selection){183 _document.execCommand('inserthtml',!1,_html);184 return;185 }186 var _range = _document.selection.createRange();187 if (!!_range.pasteHTML){_range.pasteHTML(_html);return;}188 _document.execCommand('delete',!1,null);189 _document.selection.createRange().pasteHTML(_html);190 };191 /**192 * 内容初步过滤193 * @param {Object} _html194 */195 _p.__filterContent = function(_html,_keepClass){196 var _filterHTML;197 if (_keepClass){198 _filterHTML = (_html||'').replace(__empty,'').replace(__reg_ccm,'');199 }else{200 _filterHTML = (_html||'').replace(__empty,'').replace(__reg_cls0,'').replace(__reg_cls1,'').replace(__reg_cls2,'').replace(__reg_ccm,'');201 }202 _filterHTML = !_p.__filterContentPath?_filterHTML:_p.__filterContentPath(_filterHTML);203 return _filterHTML;204 };205 /**206 * 过滤除了background-color以外的所有样式207 * @param {[type]} _html [description]208 * @return {[type]} [description]209 */210 _p.__filterContentStyle = (function(){211 var _regMap = { 0:/(?:<[^>]* style)="([^"]*)"/gi,212 1:/(?:<[^>]* style)='([^']*)'/gi,213 2:/(?:<[^>]* style)=([^>\s]*)/gi};214 var _doFilter = function(_reg,_html){215 _html = _html.replace(_regMap[_reg],function(_a,_b,_c){216 var _prefix = _a.split('style')[0];217 if(_b.match(__reg_bgc)!=null){218 var _str0 = '';219 var _bgc = _b.replace(__reg_bgc,function(_str,_sstr,_index){220 return _str0 += _str;221 }._$bind(this));222 return _prefix + ' style="' + _str0 + '"';223 }else{224 return _prefix;225 }226 }._$bind(this));227 return _html;228 };229 return function(_html){230 // IE多种情况同时出现231 _html = _doFilter(0,_html);232 _html = _doFilter(1,_html);233 _html = _doFilter(2,_html);234 return _html;235 };236 })();237 return _p;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.pdf({path: 'google.pdf', format: 'A4'});8 await browser.close();9})();10const puppeteer = require('puppeteer');11const fs = require('fs');12const path = require('path');13(async () => {14 const browser = await puppeteer.launch();15 const page = await browser.newPage();16 await page.pdf({path: 'google.pdf', format: 'A4'});17 await browser.close();18})();19const puppeteer = require('puppeteer');20const fs = require('fs');21const path = require('path');22(async () => {23 const browser = await puppeteer.launch();24 const page = await browser.newPage();25 await page.pdf({path: 'google.pdf', format: 'A4'});26 await browser.close();27})();28const puppeteer = require('puppeteer');29const fs = require('fs');30const path = require('path');31(async () => {32 const browser = await puppeteer.launch();33 const page = await browser.newPage();34 await page.pdf({path: 'google.pdf', format: 'A4'});35 await browser.close();36})();37const puppeteer = require('puppeteer');38const fs = require('fs');39const path = require('path');40(async () => {41 const browser = await puppeteer.launch();42 const page = await browser.newPage();43 await page.pdf({path: 'google.pdf', format: 'A4'});44 await browser.close();45})();46const puppeteer = require('puppeteer');

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.pdf({path: 'test.pdf', format: 'A4'});7 await browser.close();8})();9import Document, { Html, Head, Main, NextScript } from 'next/document';10class MyDocument extends Document {11 static async getInitialProps(ctx) {12 const initialProps = await Document.getInitialProps(ctx);13 return { ...initialProps };14 }15 render() {16 return (17 );18 }19}20export default MyDocument;21import App from 'next/app';22import Head from 'next/head';23import { ThemeProvider } from 'styled-components';24import { GlobalStyle } from '../styles/global';25import theme from '../styles/theme';26class MyApp extends App {27 render() {28 const { Component, pageProps } = this.props;29 return (30 <ThemeProvider theme={theme}>31 <Component {...pageProps} />32 );33 }34}35export default MyApp;36import React from 'react';37const Index = () => {38 return (39 );40};41export default Index;42const colors = {43};44const theme = {45 fonts: {

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { promisify } = require('util');5const writeFile = promisify(fs.writeFile);6const appendFile = promisify(fs.appendFile);7const unlinkFile = promisify(fs.unlink);8(async () => {9 const browser = await puppeteer.launch({ headless: true });10 const page = await browser.newPage();11 const html = await page.content();12 await writeFile(path.join(__dirname, 'google.html'), html);13 await appendFile(path.join(__dirname, 'google.html'), html);14 await unlinkFile(path.join(__dirname, 'google.html'));15 await browser.close();16})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.pdf({path: 'google.pdf', format: 'A4'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.pdf({path: 'google.pdf', format: 'A4'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.pdf({path: 'google.pdf', format: 'A4'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.pdf({path: 'google.pdf', format: 'A4'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.pdf({path: 'google.pdf', format: 'A4'});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.goto('

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 Puppeteer 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